在之前的文章《Springboot整合mybatis的多数据源配置与使用(XML版)》中以及比较详细地介绍了整个项目建立的流程,因此该篇侧重不同的部分的叙述,相同部分还请移步XML版,当然看源码基本也能很容易理解的,源码将在文末给出。
注解版自然就没有各类xml文件了,那么你可能会问,dao层或者说mapper层到数据库的映射怎么处理,当然是加个简单的注解就能搞定。
配置文件:
spring.datasource.primary.driverClassName = com.mysql.jdbc.Driver
spring.datasource.primary.url = jdbc:mysql://localhost:3306/mybatis1?useUnicode=true&characterEncoding=utf-8
spring.datasource.primary.username = root
spring.datasource.primary.password = root
spring.datasource.secondary.driverClassName = com.mysql.jdbc.Driver
spring.datasource.secondary.url = jdbc:mysql://localhost:3306/mybatis2?useUnicode=true&characterEncoding=utf-8
spring.datasource.secondary.username = root
spring.datasource.secondary.password = root
相比XML版中的接口实现在xml文件中定义,因此,在mapper接口层只需要定义几个方法就可以了。那么在注解版,就需要在方法上加注解以实现到数据库的映射。UserMapper1(UserMapper2类同)的接口实现文件如下:
package com.springboot.multi_resources_mybaits.mapper.map1;
import com.springboot.multi_resources_mybaits.entity.User;
import com.springboot.multi_resources_mybaits.enums.AuthorityEnum;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Mapper
public interface UserMapper1 {
//如果没有返回结果则不需要加Result解析,在Sql语句中必须使用标准的语句,想userName是允许的
@Select("SELECT * FROM user")
@Results({
@Result(property = "userName",column = "user_name"),
@Result(property = "authority",column = "authority",javaType = AuthorityEnum.class)
})
List<User> findAll();
@Insert("INSERT INTO user(user_name,authority) VALUES(#{userName},#{authority})")
@Results({
@Result(property = "userName",column = "user_name"),
@Result(property = "authority",column = "authority",javaType = AuthorityEnum.class)
})
void addOne(User user);
@Select("SELECT * FROM user WHERE id=#{id}")
@Results({
@Result(column = "user_name",property = "userName"),
@Result(column = "authority",property = "authority",javaType = AuthorityEnum.class)
})
User findOne(Integer id);
@Update("UPDATE user SET user_name = #{userName},authority = #{authority} WHERE id = #{id}")
void updateOne(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void delOne(Integer id);
}
需要注意的是在映射的过程中,数据库并不能识别UserName类似这样的字段(数据库的语法格式一般为user_name),因此,需要转义,将返回的user_name字段转换为UserName,使程序能识别,语法如下:
@Results({
@Result(column = "user_name",property = "userName"),
@Result(column = "authority",property = "authority",javaType = AuthorityEnum.class)
})
在没有结果返回时,则不需要映射。
源码链接