SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML和Mapper注解混用版

笔者在 SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML版SpringBoot使用HikriCP数据源连接池整合Mybatis,Mappper注解版中分别展示了mybatis注解版和XML如何和SpringBoot整合。

今天笔者就来演示混用版的使用,其实混用版就是在XML版直接用注解就好。

数据源pom.xml文件配置application.propertiesUser.java实体类、项目结构和XML版一模一样,详情点上面链接查看

下面贴上不一样的

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.wangye.spbootmybatis3.mapper.UserMapper">

    <select id="getUserById1" resultType="com.wangye.spbootmybatis3.model.User">
        select
            id as id,
            name as name,
            age as age
        from
            user
        where
            id = #{id}
    </select>

</mapper>

UserMapper.java

@Repository
public interface UserMapper {

    User getUserById1(@Param("id") Long id);

    @Select({"<script>",
            "select",
            "   id as id,",
            "   name as name,",
            "   age as age",
            "from",
            "   user",
            "<where>",
            "   <if test ='id != null'>",
            "   and",
            "       id = #{id}",
            "   </if>",
            "</where>",
            "</script>"})
    User getUserById(@Param("id") Long id);
}

UserService.java:

@Service
public class UserService {


    private UserMapper userMapper;

    // Spring推荐在不强制依赖的时候,使用这种方式注入
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User getUserById1(Long id) {

        return userMapper.getUserById1(id);
    }

    public User getUserById(Long id) {

        return userMapper.getUserById(id);
    }
}

UserController.java:

@RestController
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/getUserById1/{id}")
    public User getUserById1(@PathVariable("id") Long id){
        return userService.getUserById1(id);
    }

    @RequestMapping("/getUserById/{id}")
    public User getUserById(@PathVariable("id") Long id){
        return userService.getUserById(id);
    }
}

启动类:

@SpringBootApplication
@MapperScan("com.wangye.spbootmybatis3.mapper")
public class SpbootMybatis3Application {

    public static void main(String[] args) {
        SpringApplication.run(SpbootMybatis3Application.class, args);
    }

}

接下来启动项目,然后分别访问接口,就能返回响应的json数据。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值