SpringBoot整合Mybatis之Annotation

本文详细介绍了如何在SpringBoot项目中使用注解方式整合Mybatis,包括配置文件设置、Mapper接口定义、动态SQL实现及测试方法。通过具体代码示例,展示了插入、更新、删除和查询操作。

首先需要下载前面一篇文章的代码,在前一章代码上进行修改.

SpringBoot整合Mybatis(注解方式)

复制前一个项目,修改配置文件,mybatis的相关配置为:

mybatis:
  type-aliases-package: con.mybatis.springboot_mybatis.model
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

使用注解方式修改mapper

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users")
    @Results({
            @Result(property = "userSex", column="user_sex",javaType = UserSexEnum.class),
            @Result(property = "nickName", column = "nick_name",javaType = String.class)
    })
    List<User> getAll();

    @SelectProvider(type = UserSql.class,method = "getList")
    List<User> getList(UserParam userParam);

    @SelectProvider(type = UserSql.class,method = "getCount")
    int getCount(UserParam userParam);

    /*注意$与#的区别*/

    @Select("SELECT * FROM users WHERE user_sex = #{user_sex}")
    List<User> getListByUserSex(@Param("user_sex") String userSex);

    @Select("SELECT * FROM users WHERE username=#{username} AND user_sex = #{user_sex}")
    List<User> getListByNameAndSex(Map<String, Object> map);

    @Select("SELECT * FROM users WHERE ID = #{id}")
    @Results({
            @Result(property = "userSex", column="user_sex",javaType = UserSexEnum.class),
            @Result(property = "nickName", column = "nick_name",javaType = String.class)
    })
    User getOne(Long id);

    @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName},#{passWord},#{userSex})")
    void insert(User user);

    @UpdateProvider(type = UserSql.class,method = "update")
    int update(User user);

    @Update({"<script> ",
            "UPDATE users ",
            "<set>" ,
            " <if test='userName != null'>userName=#{userName},</if>" ,
            " <if test='nickName != null'>nick_name=#{nickName},</if>" ,
            " </set> ",
            "where id=#{id} " ,
            "</script>"})
    int updateUser(User user);

    @Delete("DELETE FROM users WHERE id = #{id}")
    int delete(Long id);

}

动态sql类:

public class UserSql {

    private static final Logger log = LoggerFactory.getLogger(UserSql.class);

    public String getList(UserParam userParam) {
        StringBuffer sql = new StringBuffer("select id, userName, passWord, user_sex as userSex, nick_name as nickName");
        sql.append(" from users where 1=1 ");
        if (userParam != null) {
            if (!StringUtils.isEmpty(userParam.getUserName())) {
                sql.append(" and userName = #{userName}");
            }
            if (!StringUtils.isEmpty(userParam.getUserSex())) {
                sql.append(" and user_sex = #{userSex}");
            }
        }
        sql.append(" order by id desc");
        sql.append(" limit " + userParam.getBeginLine() + "," + userParam.getPageSize());
        log.info("getList sql is :" +sql.toString());
        return sql.toString();
    }

    public String getCount(UserParam userParam) {
        String sql= new SQL(){{
            SELECT("count(1)");
            FROM("users");
            if (!StringUtils.isEmpty(userParam.getUserName())) {
                WHERE("userName = #{userName}");
            }
            if (!StringUtils.isEmpty(userParam.getUserSex())) {
                WHERE("user_sex = #{userSex}");
            }
            //从这个toString可以看出,其内部使用高效的StringBuilder实现SQL拼接
        }}.toString();

        log.info("getCount sql is :" +sql);
        return sql;
    }

    public String update(User user) {
        String sql = new SQL() {{
            UPDATE("users");
            if(!StringUtils.isEmpty(user.getNickName())){
                SET("nick_name=#{nickName}");
            }
            if(!StringUtils.isEmpty(user.getUserName())) {
                SET("userName=#{userName}");
            }
            if(!StringUtils.isEmpty(user.getPassWord())) {
                SET("passWord=#{passWord}");
            }
            if(!StringUtils.isEmpty(user.getUserSex())) {
                SET("user_sex=#{userSex}");
            }
            WHERE("id=#{id}");
        }}.toString();
        return sql;
    }
}

最后测试类(多添加了两个方法,一个传递String,另一个是传递map):


@SpringBootTest
@RunWith(SpringRunner.class)
public class MybatisAnnoTest {

    @Resource
    private UserMapper userMapper;

    @Test
    public void testInsert()  {
        userMapper.insert(new User("dd", "a123456", UserSexEnum.MAN));
        // The total number of data in the database
        Assert.assertEquals(3, userMapper.getAll().size());
    }

    @Test
    public void testUpdate() {
        long id=4l;
        User user = userMapper.getOne(id);
        if(user!=null){
            System.out.println(user.toString());
            user.setNickName("wzlove");
            userMapper.update(user);
            Assert.assertTrue(("wzlove".equals(userMapper.getOne(id).getNickName())));
        }else {
            System.out.println("not find user id="+id);
        }
    }


    @Test
    public void testDelete() {
        int count=userMapper.delete(2l);
        if(count>0){
            System.out.println("delete is sucess");
        }else {
            System.out.println("delete if failed");
        }
    }

    @Test
    public void findAll(){
        UserParam userParam = new UserParam();
        userParam.setCurrentPage(0);
        userParam.setPageSize(1);
        List<User> list = userMapper.getList(userParam);
        System.out.println(list.get(0));
        Assert.assertEquals(1,list.size());
    }
    
    @Test
    public void testGetListByUserSex(){
        String userSex = "MAN";
        List<User> userLists = userMapper.getListByUserSex(userSex);
        Assert.assertEquals(2,userLists.size());
    }

    @Test
    public void testGetListByNameAndSex(){
        Map<String,Object> condition = new HashMap<>(2);
        condition.put("username","dd");
        condition.put("user_sex","MAN");
        List<User> userList = userMapper.getListByNameAndSex(condition);
        Assert.assertEquals(1,userList.size());
    }
}

SpringBoot整合Mybatis到这里就总结完了,这里都没有考虑到多数据源的问题,所以有需求的看pdf文档就好.

SpringBoot整合Mybatis也就是两种方式,一种是xml的方式,另一种是注解的方式. 注解方式中需要注意的是动态sql的写法. xml中注意的是mapper的路径等的注意. 了解myabtis的一个执行流程. SqlSessionFactoryBuilder -> SqlSessionFactory -> SqlSession -> Executor -> sql对象 -> 执行返回结果,完毕

源码地址: https://github.com/MissWangLove/SpringBoot

转载于:https://www.cnblogs.com/wadmwz/p/10309319.html

### 如何在 Spring Boot 中整合 MyBatis 在 Spring Boot 中整合 MyBatis,需要完成以下几个关键点:配置启动类、定义 Mapper 接口、创建实体类以及编写 Controller 层代码。以下是具体实现方法: #### 1. 配置启动类 为了使 MyBatis 的 Mapper 接口能够被正确扫描并注入到 Spring 容器中,需要在启动类上添加 `@MapperScan` 注解,并指定 Mapper 接口所在的包路径。 ```java package com.example; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.example.mapper") // 指定 Mapper 接口所在的包路径 public class SpringbootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisApplication.class, args); } } ``` 上述代码通过 `@MapperScan` 注解指定了 Mapper 接口的包路径,确保 MyBatis 能够自动扫描并注册这些接口[^1]。 #### 2. 定义 Mapper 接口 Mapper 接口是 MyBatis 的核心组件之一,用于定义与数据库交互的操作。以下是一个示例 Mapper 接口: ```java package com.example.mapper; import org.apache.ibatis.annotations.Select; import com.example.entity.User; public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User findById(int id); } ``` 此接口中的 `@Select` 注解定义了一个简单的 SQL 查询语句,用于根据用户 ID 查询用户信息[^4]。 #### 3. 创建实体类 实体类用于映射数据库表中的记录。以下是一个示例实体类: ```java package com.example.entity; public class User { private Integer id; private String name; private String email; // Getter 和 Setter 方法 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } ``` 如果需要更复杂的映射规则,可以使用 `@Table` 和 `@Id` 等注解来标注表名和主键字段[^3]。 #### 4. 编写 Controller 层 Controller 层负责处理 HTTP 请求并与 Service 层或 Mapper 层进行交互。以下是一个示例 Controller: ```java package com.example.controller; import com.example.entity.User; import com.example.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/user/{id}") public User getUserById(@PathVariable int id) { return userMapper.findById(id); } } ``` 上述代码定义了一个 RESTful API,允许通过 `/user/{id}` 路径查询指定 ID 的用户信息[^4]。 --- #### 注意事项 - 如果使用的是 `tk.mybatis.mapper` 提供的功能,则需要将 `org.mybatis.spring.annotation.MapperScan` 替换为 `tk.mybatis.spring.annotation.MapperScan`。 - 确保项目中引入了正确的依赖项,例如 MyBatis 和 Spring Boot 的相关 Starter 包。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值