SpringBoot--整合MyBatis(注解方式)

短命女 2021-08-13 21:04 682阅读 0赞

整合MyBatis(注解方式)

Users表结构

  1. CREATE TABLE `users` (
  2. `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  3. `username` varchar(32) DEFAULT NULL COMMENT '用户名',
  4. `password` varchar(32) DEFAULT NULL COMMENT '密码',
  5. `sex` varchar(32) DEFAULT NULL,
  6. `nick_name` varchar(32) DEFAULT NULL,
  7. PRIMARY KEY (`id`),
  8. UNIQUE KEY `username` (`username`) USING HASH
  9. ) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;

添加pom文件

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.lynch.springboot</groupId>
  4. <artifactId>spring-boot-mybatis-annotation</artifactId>
  5. <version>0.0.1-SNAPSHOT</version>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>1.5.10.RELEASE</version>
  10. </parent>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <java.version>1.8</java.version>
  14. </properties>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-web</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.mybatis.spring.boot</groupId>
  31. <artifactId>mybatis-spring-boot-starter</artifactId>
  32. <version>1.3.2</version>
  33. </dependency>
  34. <!-- mybatis分页插件 -->
  35. <dependency>
  36. <groupId>com.github.pagehelper</groupId>
  37. <artifactId>pagehelper-spring-boot-starter</artifactId>
  38. <version>1.1.1</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>mysql</groupId>
  42. <artifactId>mysql-connector-java</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.boot</groupId>
  46. <artifactId>spring-boot-devtools</artifactId>
  47. <optional>true</optional>
  48. </dependency>
  49. </dependencies>
  50. <build>
  51. <plugins>
  52. <plugin>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-maven-plugin</artifactId>
  55. </plugin>
  56. </plugins>
  57. </build>
  58. </project>

application.properties 添加相关配置

  1. #mybatis.type-aliases-package=com.lynch.entity
  2. spring.datasource.driverClassName = com.mysql.jdbc.Driver
  3. spring.datasource.url = jdbc:mysql://192.168.1.149:3306/aa?useUnicode=true&characterEncoding=utf-8&useSSL=false
  4. spring.datasource.username = root
  5. spring.datasource.password = attack

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对于开发人员不用管,直接拿来使用即可。

在启动类中添加对mapper包扫描@MapperScan

  1. package com.lynch;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan("com.lynch.mapper")
  7. public class Application {
  8. public static void main(String[] args) {
  9. SpringApplication.run(Application.class, args);
  10. }
  11. }

或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个mapper加个注解也挺麻烦的。

Mapper

  1. package com.lynch.mapper;
  2. import java.util.List;
  3. import org.apache.ibatis.annotations.Delete;
  4. import org.apache.ibatis.annotations.Insert;
  5. import org.apache.ibatis.annotations.InsertProvider;
  6. import org.apache.ibatis.annotations.Param;
  7. import org.apache.ibatis.annotations.Result;
  8. import org.apache.ibatis.annotations.Results;
  9. import org.apache.ibatis.annotations.Select;
  10. import org.apache.ibatis.annotations.SelectProvider;
  11. import org.apache.ibatis.annotations.Update;
  12. import org.apache.ibatis.annotations.UpdateProvider;
  13. import com.lynch.entity.UserEntity;
  14. import com.lynch.enums.SexEnum;
  15. public interface UserMapper {
  16. @Select("SELECT * FROM users")
  17. @Results({ @Result(property = "sex", column = "sex", javaType = SexEnum.class),
  18. @Result(property = "nickName", column = "nick_name") })
  19. List<UserEntity> getAll();
  20. @Select("SELECT * FROM users WHERE id = #{id}")
  21. @Results({ @Result(property = "sex", column = "sex", javaType = SexEnum.class),
  22. @Result(property = "nickName", column = "nick_name") })
  23. UserEntity getOne(Long id);
  24. @Insert("insert into users(username,password,sex) values(#{username}, #{password}, #{sex})")
  25. int insert(UserEntity user);
  26. @Update("UPDATE users SET userName=#{username},nick_name=#{nickName} WHERE id =#{id}")
  27. void update(UserEntity user);
  28. @Delete("DELETE FROM users WHERE id =#{id}")
  29. void delete(Long id);
  30. @InsertProvider(type=UserProvider.class, method = "batchInsert")
  31. int batchInsert(@Param("userList")List<UserEntity> userList);
  32. @SelectProvider(type = UserProvider.class, method = "queryUser")
  33. @Results({
  34. @Result(property = "sex", column = "sex", javaType = SexEnum.class),
  35. @Result(property = "nickName", column = "nick_name")
  36. })
  37. public List<UserEntity> queryUser(UserEntity user);
  38. @UpdateProvider(type = UserProvider.class, method = "updateUser")
  39. public int updateUser(@Param("U")UserEntity user);
  40. }
  41. package com.lynch.mapper;
  42. import java.util.List;
  43. import java.util.Map;
  44. import org.apache.ibatis.annotations.Param;
  45. import org.apache.ibatis.jdbc.SQL;
  46. import com.github.pagehelper.util.StringUtil;
  47. import com.lynch.entity.UserEntity;
  48. /** * 利用@Provider实现动态SQL * * @author Lynch * */
  49. public class UserProvider {
  50. public String queryUser(UserEntity user) {
  51. StringBuffer sql = new StringBuffer("select * from users where 1=1 ");
  52. if(StringUtil.isNotEmpty(user.getUsername())) {
  53. sql.append(String.format("and username like '%s'", "%"+user.getUsername()+"%"));
  54. }
  55. return sql.toString();
  56. }
  57. public String batchInsert(Map map) {
  58. List<UserEntity> userList = (List<UserEntity>)map.get("userList");
  59. StringBuffer sql = new StringBuffer("insert into users (username,password) values ");
  60. for(UserEntity user : userList) {
  61. sql.append(String.format("('%s', '%s'),", user.getUsername(), user.getPassword()));
  62. }
  63. sql = sql.deleteCharAt(sql.length() -1);
  64. System.out.println(sql.toString());
  65. return sql.toString();
  66. }
  67. public String updateUser(@Param("U")UserEntity user) {
  68. SQL sql = new SQL(){ {
  69. UPDATE("users");
  70. if (StringUtil.isNotEmpty(user.getNickName())){
  71. SET("nick_name = #{U.nickName}");
  72. }
  73. WHERE("id = #{U.id}");
  74. }};
  75. return sql.toString();
  76. }
  77. }

注意,使用#符号和$符号的不同:

  1. // This example creates a prepared statement, something like select * from teacher where name = ?;
  2. @Select("Select * from teacher where name = #{name}")
  3. Teacher selectTeachForGivenName(@Param("name") String name);
  4. // This example creates n inlined statement, something like select * from teacher where name = 'someName';
  5. @Select("Select * from teacher where name = '${name}'")
  6. Teacher selectTeachForGivenName(@Param("name") String name);

单元测试

  1. package com.lynch.mapper;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import com.lynch.entity.UserEntity;
  10. import com.lynch.enums.SexEnum;
  11. @RunWith(SpringRunner.class)
  12. @SpringBootTest
  13. public class UserMapperTest {
  14. @Autowired
  15. private UserMapper userMapper;
  16. @Test
  17. public void insert() throws Exception {
  18. int result = 0;
  19. try {
  20. result = userMapper.insert(new UserEntity("lisi", "123456", SexEnum.MAN));
  21. } catch (Exception e) {
  22. System.out.println(e.getMessage().indexOf("ConstraintViolationException"));
  23. }
  24. System.out.println("result=" + result);
  25. }
  26. @Test
  27. public void batchInsert() throws Exception {
  28. List<UserEntity> userList = new ArrayList<UserEntity>();
  29. userList.add(new UserEntity("a","a",SexEnum.MAN));
  30. userList.add(new UserEntity("c","b",SexEnum.MAN));
  31. userList.add(new UserEntity("b","b",SexEnum.WOMAN));
  32. System.out.println("result=" + userMapper.batchInsert(userList));
  33. }
  34. @Test
  35. public void getAll() throws Exception {
  36. List<UserEntity> users = userMapper.getAll();
  37. System.out.println(users.toString());
  38. }
  39. @Test
  40. public void testUpdate() throws Exception {
  41. UserEntity user = userMapper.getOne(45L);
  42. System.out.println(user.toString());
  43. user.setNickName("neo");
  44. user.setSex(SexEnum.WOMAN);
  45. userMapper.update(user);
  46. }
  47. @Test
  48. public void queryUser() throws Exception {
  49. UserEntity user = new UserEntity();
  50. user.setUsername("l");
  51. System.out.println(userMapper.queryUser(user));
  52. }
  53. @Test
  54. public void updateUser() throws Exception {
  55. UserEntity user = new UserEntity();
  56. user.setId(45L);
  57. user.setNickName("aaa");
  58. System.out.println(userMapper.updateUser(user));
  59. }
  60. }

发表评论

表情:
评论列表 (有 0 条评论,682人围观)

还没有评论,来说两句吧...

相关阅读