早上好。我有一个多线程应用程序,它可以访问对DB mySql的读写。使用myBatis。对于会话管理,它编写了以下类:
public class ConnectionMySQL {
private static final Logger log = Logger.getLogger(ConnectionMySQL.class);
private static SqlSessionFactory sqlSessionFactory;
private ConnectionMySQL() {
}
static {
try {
String resource = "com/application/dao/config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Throwable e) {
log.error("Impossibile avviare la connessione sul DB", e);
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
}每当我运行查询时,都会运行以下操作:
public void start() {
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())+" ***** Start ****");
long start = System.currentTimeMillis();
SqlSession sessione = ConnectionMySQL.getSession().openSession();
try {
..........
..........
}catch (MessagingException e) {
log.warn("Impossibile inviare messaggio di notifica");
}finally {
sessione.close();
long end = System.currentTimeMillis();
log.info("Numero thread :"+numeroThread+" - Tempo di esecuzione "+ (end - start) +" ms");
}
}我在MySQL和myBatis方面不是很有经验。我想知道这是否是用myBatis处理多线程的正确方法。谢谢。
发布于 2015-12-21 12:35:52
SqlSessionFactory是线程安全的。把它传过来。你使用它是安全的。
SqlSession是而不是线程安全,应该只在方法作用域中使用。
我建议使用DAO模式来构造数据库代码:
public MyPojo select(int primaryKey) {
try (SqlSession session = sqlSessionFactory.openSession()) {
MyPojoMapper mapper = session.getMapper(MyPojoMapper.class);
return mapper.select(primaryKey);
}
}https://stackoverflow.com/questions/33853725
复制相似问题