笔者在 SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML版和SpringBoot使用HikriCP数据源连接池整合Mybatis,Mappper注解版中分别展示了mybatis注解版和XML如何和SpringBoot整合。
今天笔者就来演示混用版的使用,其实混用版就是在XML版直接用注解就好。
数据源pom.xml文件配置、application.properties、User.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数据。