服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - MyBatis使用注解开发和无主配置文件开发的情况

MyBatis使用注解开发和无主配置文件开发的情况

2021-08-24 11:18爱喝椰汁的木木 Java教程

这篇文章主要介绍了MyBatis使用注解开发和无主配置文件开发的情况,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

MyBatis使用注解开发时就不在需要和接口对应的映射文件了

主要有以下几个注解

@Select() @Insert @Update() @Delete()

代码演示

项目结构:

MyBatis使用注解开发和无主配置文件开发的情况

数据库表设计

MyBatis使用注解开发和无主配置文件开发的情况

实体类

User

  1. public class User implements Serializable {
  2.  
  3. private long userId;
  4. private String userName;
  5. private Date birthday;
  6. private String sex;
  7. private String address;
  8.  
  9. getter setter toString

主配置文件mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5.  
  6. <configuration>
  7. <properties resource="db.properties"/>
  8.  
  9. <!--开启驼峰命名-->
  10. <settings>
  11. <setting name="mapUnderscoreToCamelCase" value="true"/>
  12. </settings>
  13.  
  14. <!--起别名 typeAliases-->
  15. <typeAliases>
  16. <package name="com.codeyancy.cn.entity"/>
  17. </typeAliases>
  18.  
  19. <environments default="development">
  20. <environment id="development">
  21. <transactionManager type="JDBC"/>
  22. <dataSource type="POOLED">
  23. <property name="driver" value="${jdbc.driverClassName}"/>
  24. <property name="url" value="${jdbc.url}"/>
  25. <property name="username" value="${jdbc.username}"/>
  26. <property name="password" value="${jdbc.password}"/>
  27. </dataSource>
  28. </environment>
  29. </environments>
  30.  
  31. <mappers>
  32. <!--包扫描-->
  33. <package name="com.codeyancy.cn.mapper"/>
  34. </mappers>
  35. </configuration>

db.properties

  1. jdbc.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/web_test?characterEncoding=utf-8
  3. jdbc.username=root
  4. jdbc.password=666

mapper接口

  1. public interface UserMapper {
  2.  
  3. /**
  4. * 查询所有用户信息
  5. */
  6. @Select("select * from user")
  7. List<User> findAll();
  8.  
  9. /**
  10. * 根据id查询用户信息
  11. */
  12. @Select("select * from user where user_id=#{userId}")
  13. User findById(Integer id);
  14.  
  15. /**
  16. * 新增
  17. */
  18. @Insert("insert into user (user_name,birthday,sex,address) values (#{userName},#{birthday},#{sex},#{address})")
  19. void insertUser(User user);
  20.  
  21. /**
  22. * 修改
  23. */
  24. @Update("update user set user_name=#{userName},birthday=#{birthday},sex=#{sex},address=#{address} where user_id=#{userId}")
  25. void updateUser(User user);
  26.  
  27. /**
  28. * 删除
  29. */
  30. @Delete("delete from user where user_id=#{userId}")
  31. void deleteUserById(Integer id);
  32.  
  33. /**
  34. * 通过id或者名字模糊查询
  35. * 多个参数查询方式二:@Param
  36. */
  37. @Select("select * from user where user_id=#{id} or user_name like '%${name}%'")
  38. List<User> select(@Param("id") Integer id, @Param("name") String name);
  39. }

测试类
Demo

  1. public class Demo {
  2.  
  3. public static void main(String[] args) {
  4. String path="mybatis-config.xml";
  5. InputStream resourceAsStream = null;
  6. try {
  7. resourceAsStream = Resources.getResourceAsStream(path);
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  12. SqlSession sqlSession = sqlSessionFactory.openSession(true);
  13. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  14.  
  15. //System.out.println(mapper.findAll());
  16. //System.out.println(mapper.findById(1));
  17.  
  18. /*User user = new User();
  19. user.setUserName("老皮");
  20. user.setBirthday(new Date());
  21. mapper.insertUser(user);*/
  22.  
  23. /*User user = new User();
  24. user.setUserName("李立林");
  25. user.setBirthday(new Date());
  26. user.setUserId(27);
  27. mapper.updateUser(user);*/
  28.  
  29. //mapper.deleteUserById(27);
  30.  
  31. System.out.println(mapper.select(1, "麻"));
  32.  
  33. sqlSession.close();
  34. try {
  35. resourceAsStream.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }

使用注解开发的一些问题

如果数据库字段名和实体类的属性名不一致,也不遵循驼峰命名。这种情况下,如果是使用映射文件可以用resultMap来解决。

但是注解开发也是可以解决的:

  1. * 如果数据库列名和实体类属性名不一致或者没有开启驼峰命名,可以使用@Results解决这个问题
  2. *
  3. * @Select("sql语句")
  4. * @Results({
  5. * @Result(column="",property=""),
  6. * @Result(column="",property=""),
  7. * @Result(column="",property=""),
  8. * })
  9. *
  10. * 使用注解也可以一对一,一对多
  11. * @Result(column="",property="",one=@One("sql语句")), 一对一
  12. * @Result(column="",property="",one=@Many("sql语句")), 一对多

在mybatis的使用中,主配置文件mybatis-config.xml 是十分重要的,那么能不能不使用主配置文件进行mybatis开发呢?

可以!!!

在官网中清楚的指出了可以使用java代码来代替xml主配置文件----》如下

MyBatis使用注解开发和无主配置文件开发的情况

尝试使用java类来代替主配置文件

MyBatisDemo

  1. /**
  2. *使用java类代替mybatis-config.xml主配置文件
  3. */
  4. public class MyBatisDemo {
  5. public static void main(String[] args) {
  6. //加载db.properties文件方式一
  7. // InputStream resourceAsStream = MyBatisDemo.class.getClassLoader().getResourceAsStream("db.properties");
  8. // Properties properties = new Properties();
  9. // try {
  10. // properties.load(resourceAsStream);
  11. // } catch (IOException e) {
  12. // e.printStackTrace();
  13. // }
  14. // String drive = properties.getProperty("jdbc.driverClassName");
  15. // String url = properties.getProperty("jdbc.url");
  16. // String name = properties.getProperty("jdbc.username");
  17. // String pass = properties.getProperty("jdbc.password");
  18. // DataSource dataSource = new PooledDataSource(drive,url,name,pass);
  19.  
  20. //加载db.properties文件方式二(推荐)
  21. ResourceBundle bundle = ResourceBundle.getBundle("db");
  22. String drive = bundle.getString("jdbc.driverClassName");
  23. String url = bundle.getString("jdbc.url");
  24. String name = bundle.getString("jdbc.username");
  25. String pass = bundle.getString("jdbc.password");
  26.  
  27. DataSource dataSource = new PooledDataSource(drive,url,name,pass);
  28. TransactionFactory transactionFactory = new JdbcTransactionFactory();
  29. Environment environment = new Environment("development", transactionFactory, dataSource);
  30. Configuration configuration = new Configuration(environment);
  31. //开启包扫描
  32. configuration.addMappers("com.codeyancy.cn.mapper");
  33. //开启驼峰命名
  34. configuration.setMapUnderscoreToCamelCase(true);
  35. //设置别名
  36. //configuration.getTypeAliasRegistry().registerAliases("com.codeyancy.cn.entity");
  37. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
  38. SqlSession sqlSession = sqlSessionFactory.openSession(true);
  39. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  40.  
  41. //打印查询所有
  42. System.out.println(mapper.findAll());
  43.  
  44. sqlSession.close();
  45. }
  46. }

简单测试后,是可以使用的。

到此这篇关于MyBatis使用注解开发和无主配置文件开发的情况的文章就介绍到这了,更多相关MyBatis注解开发无主配置文件内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_45503643/article/details/114763577

延伸 · 阅读

精彩推荐