mybatis3之后,支持不适用xml来写Sql
官方文档上说,sql可以写成像下面这样:
@Update({"<script>",
"update Author",
" <set>",
" <if test='username != null'>username=#{username},</if>",
" <if test='password != null'>password=#{password},</if>",
" <if test='email != null'>email=#{email},</if>",
" <if test='bio != null'>bio=#{bio}</if>",
" </set>",
"where id=#{id}",
"</script>"})
void updateAuthorValues(Author author);
上面摘自mybatis动态SQL
笔者在SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML版中就已经配置了数据源,这篇笔者仍旧使用原来的数据源
pom.xml配置是和原来的一样,User.java也是和原来的一样
下面上一些必要的代码:
首先是application.properties
# 数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=false
# 数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=root
#自动提交 默认值true
spring.datasource.hikari.auto-commit=true
#此属性控制客户端(即您)将等待来自池的连接的最大毫秒数。 默认值30000(30秒)
spring.datasource.hikari.connection-timeout=30000
#此属性控制允许连接在池中闲置的最长时间。 默认值600000(10分钟),此设置仅适用于minimumIdle定义为小于maximumPoolSize。
spring.datasource.hikari.idle-timeout=600000
#此属性控制池中连接的最大生存期。 1800000(30分钟)
spring.datasource.hikari.max-lifetime=1800000
#该属性控制HikariCP尝试在池中维护的最小空闲连接数。不推荐使用这个,默认是和maximum-pool-size相等
spring.datasource.hikari.minimum-idle=100
#此属性控制池允许达到的最大大小,包括空闲和正在使用的连接。默认值10
spring.datasource.hikari.maximum-pool-size=100
#mybatis对应的映射文件路径
#mybatis.mapper-locations=classpath:mapper/*.xml
#mybatis对应的实体类
mybatis.type-aliases-package=com.wangye.spbootmybatis2.model
注意:mybatis.mapper-locations=classpath:mapper/*.xml 这个配置,笔者前面已经加了#号注释掉了,说明已经不需要xml文件了。
下面看看项目的目录结构:
接下来重头戏来了
UserMapper.java
@Repository
public interface UserMapper {
@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);
}
注意:笔者使用了注解!!!使用了注解写sql。而且写的是动态的sql
UserService.java
@Service
public class UserService {
private UserMapper userMapper;
// Spring推荐在不强制依赖的时候,使用这种方式注入
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
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("/getUserById/{id}")
public User getUserById(@PathVariable("id") Long id){
return userService.getUserById(id);
}
}
最后是启动类:
@SpringBootApplication
@MapperScan("com.wangye.spbootmybatis2.mapper")
public class SpbootMybatis2Application {
public static void main(String[] args) {
SpringApplication.run(SpbootMybatis2Application.class, args);
}
}
注意@MapperScan("com.wangye.spbootmybatis2.mapper") 还是不能少的
最后就是启动项目,访问该访问的接口就好了
笔者个人观点:
笔者个人不是很喜欢这种写Sql的方式,因为要不断的打双引号,要使用动态sql还要放在<script></script>标签中。这样和xml差不多。所有笔者喜欢混用方式。笔者之后会上一篇文章,说说xml和注解如何混用的