应用场景:在传输数据量较大的场景,发送方可能会将数据结果存储到sqlite中,接收方接收数据后,再从sqlite读取数据。
存在的问题:mybaits打开sqlite数据库,会占用大量内存(大概5M左右)
第一步
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="UNPOOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="设置扫描的mapper"/>
</mappers>
</configuration>
自己根据需要选择是否使用连接池。(判断原则,数据库打开一次,然后读取所有数据,就不要使用连接池,需要多次打开读取数据的话,建议使用连接池。)
第二步
private static SqlSession openSqliteSession(String url, String username, String password, String cmpId) throws IOException{
String resource = “mybatis/sqliteApplicationContext.xml”;
InputStream inputStream = Resources.getResourceAsStream(resource);
Properties properties = new Properties();
properties.setProperty("jdbc.driver", "org.sqlite.JDBC");
properties.setProperty(
"jdbc.url",
"jdbc:sqlite:" + url);
properties.setProperty("jdbc.username", password);
properties.setProperty("jdbc.password", username);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,properties);
SqlSession session = sqlSessionFactory.openSession();
return session;
}
第三步
//获取mapper实例
SomeMapper mapper = sqlSession.getMapper(SomeMapper.class);
if (null == mapper) {
throw new CompareException("获取Mapper失败");
}
//获取数据记录
Result result = mapper.getResult(id);
if (null == Result) {
throw new CompareException("获取数据记录失败");
}