MyBatis是目前java项目连接数据库的最流行的orm框架了。常用的使用方法是配置datasource,编写dao和mapper,最后通过依赖注入调用dao的方法来操作数据。本篇使用MyBatis来动态生成MyBatis的对象,动态配置数据库连接操作数据库。
使用MyBaits常规方式是在xml或者properties来配置MyBatis,但是这样会把配置参数写死。如果想要动态访问数据库,我们能自己手动实例化MyBatis对象。
还记得我们在经常在xml配置文件中,配置一个Datasource对象,设置数据连接相关参数。这里我们使用代码动态实例化一个PooledDataSource
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("123456");
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:/mapper/*Mapper.xml");
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setMapperLocations(resources);
sqlSessionFactoryBean.setDataSource(dataSource);
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
记住,这里的sqlsession生成后,请保存到一个HashMap就像一个数据库连接池一样,可以反复使用。否则,每次数据库操作都会打开一个新的数据库连接,造成数据库连接超限,导致数据库瘫痪。
SqlSession sqlsession = sqlSessionFactory.openSession();
// 调用数据库操作方法
sqlsession.close()
我们平常使用MyBatis时,会在xml或者properties文件中配置的参数,然后MyBatis会使用这些参数实例化以上对象。
动态配置了MyBatis的数据库连接,并生成MyBatis对象。接下来,就是常规的利用MyBatis的Mapper模板来实现数据的增删改查了。
public interface DynamicMapper {
List<Map<String, Object>> selectSql(@Param("tableName") String tableName, @Param("fields") String fields, @Param("whereCondition") String whereCondition, @Param("orderCondition") String orderCondition);
Integer insertSql(@Param("tableName") String tableName, @Param("result") String result);
Integer updateSql(@Param("tableName") String tableName, @Param("result") String result, @Param("whereCondition") String whereCondition);
Integer deleteSql(@Param("tableName") String tableName, @Param("whereCondition") String whereCondition);
}
<mapper namespace="com.camellibby.pangu.openapi.mapper.DynamicMapper">
<select id="selectSql" resultType="java.util.LinkedHashMap">
select ${fields} from ${tableName}
<if test="whereCondition != null and whereCondition != ''">
where ${whereCondition}
if>
<if test="orderCondition != null and orderCondition != ''">
order by ${orderCondition}
if>
select>
<insert id="insertSql">
insert into ${tableName} ${result}
insert>
<update id="updateSql">
UPDATE ${tableName} SET ${result} WHERE ${whereCondition}
update>
<delete id="deleteSql">
delete from ${tableName} WHERE ${whereCondition}
delete>
mapper>
DynamicMapper dynamicMapper = sqlsession.getMapper(DynamicMapper.class);
List<Map<String, Object>> users = dynamicMapper.selectSql(
"users",
"username, password, enabled",
"enabled=0",
"username"
);
users.forEach(user ->
user.keySet().forEach(key ->
System.out.println(key + ":" + user.get(key))
)
);
运行测试用例,进行sql查询,输出如下
03:32:46.245 [main] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@68044f4] will not be managed by Spring
03:32:46.260 [main] DEBUG DynamicMapper.selectSql - ==> Preparing: select username, password, enabled from users where enabled=0 order by username
03:32:46.338 [main] DEBUG DynamicMapper.selectSql - ==> Parameters:
03:32:46.385 [main] DEBUG DynamicMapper.selectSql - <== Total: 6
username:Chandler
password:{bcrypt}$2a$10$/8MMuGgPbNXoiMgvS3uabuQiRMW3f96wLP/ifZ3VcSHo28OuzB8Hu
enabled:false
username:Joey
password:{bcrypt}$2a$10$/8MMuGgPbNXoiMgvS3uabuQiRMW3f96wLP/ifZ3VcSHo28OuzB8Hu
enabled:false
username:Monica
password:{bcrypt}$2a$10$/8MMuGgPbNXoiMgvS3uabuQiRMW3f96wLP/ifZ3VcSHo28OuzB8Hu
enabled:false
username:Phoebe
password:{bcrypt}$2a$10$/8MMuGgPbNXoiMgvS3uabuQiRMW3f96wLP/ifZ3VcSHo28OuzB8Hu
enabled:false
username:Rachel
password:{bcrypt}$2a$10$/8MMuGgPbNXoiMgvS3uabuQiRMW3f96wLP/ifZ3VcSHo28OuzB8Hu
enabled:false
username:Ross
password:{bcrypt}$2a$10$/8MMuGgPbNXoiMgvS3uabuQiRMW3f96wLP/ifZ3VcSHo28OuzB8Hu
enabled:false