SpringBoot 整合Mybatis
整合步骤说明:
(1) Maven 中添加依赖
配置文件,在maven工程中 pom.xml中添加 mybatis 和对应的数据库(mysql、sqlserver、oracle)依赖
<!--mybatis依赖 -->
<dependency>
<grougId></grougId>
<artifactId></artifactId>
</dependency>
<!--数据库依赖 -->
<dependency>
<grougId></grougId>
<artifactId></artifactId>
</dependency>
(2) 配置文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 配置文件的根元素 -->
<configuration>
<!-- 一个配置完整的 settings 元素的示例 -->
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<!-- 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。-->
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
</configuration>
(3) 配置类
@Configuration
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "dataSouce")
public ComboPooledDataSource createDataSouce() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
//关闭连接后不自动commit
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}
@Configuration
public class SessionFactoryConfiguration {
@Value("${mapper_path}")
private String mapperPath;
@Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
@Autowired
private DataSource dataSouce;
@Value("${entity_package}")
private String entityPackage;
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
sqlSessionFactoryBean.setDataSource(dataSouce);
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
}
(4) 配置数据库连接(在application.properties文件中)
application.properties 与 application.yaml:
application.properties 与 application.yaml 文件 功能类似,SpringBoot 底层会将 application.yaml 文件转化成application.properties。
Springboot 中多环境配置文件名命名满足application-{profile}.yml 格式,其中{profile} 对应环境标识。
application-dev.yml 开发环境
application-test.yml 测试环境
application-prod.yml 生产环境
至于那个环境被加载,需要在application.yml 文件中通过spring.profiles.active 属性进行指定,其中{profile}值对应环境标识。
备注:application.properties 文件与application.yml 文件相关转化网址为:
(5) 编写实体类
@Data
public class User{
private int userid;
private String userName;
private int userAge;
private String userSex;
}
(6) 配置文件 mapper.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.example.business.mapper.UserMapper">
<resultMap id="SelectUserType" type="com.example.business.entity.Twitter">
<id property="userid" column="user_id"/>
<id property="userName" column="user_name"/>
<id property="userAge" column="user_Age"/>
<id property="userSex" column="user_Sex"/>
</resultMap>
<!-- 获取数据 -->
<select id="selectUser" resultMap="SelectUserType">
select * from user;
</select>
<!--更新数据-->
<update id="updateUser">
update user
set user_Name=#{userName}
where user_Id=#{userId};
</update>
</mapper>
(7) 接口类的实现
@Mapper
public interface UserMapper{
public List<User>SelectUserType();
}
(8) 业务逻辑方法使用
@Service
public class UserService{
@Autowired
private UserMapper userMapper;
public List<User> SelectUserType(){
return userMapper.SelectUserType()
}
}
(9) 控制层调用
@RestController
public class UserController{
@Autowired
private UserService userService;
@GetMapping("/getUserData")
public String getUserData(){
Map<String, Object> map = new HashMap<String, Object>();
List<Map> list = new ArrayList<>();
List<User> users = userService.SelectUserType();
for(User user: users){
map.put("name", user.getName);
map.put("age", user.getAge);
list.add(map);
}
String resultDic = JSON.toJSONString(list);
return resultDic; // 词典对应信息
}
}