2

Good morning. I have a multithreaded application that accesses in reading writing to a DB mySql . Use myBatis . For session management it wrote the following class:

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;
    }

}

Whenever I run a query I run these operations :

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");

    }

}

I am not very experienced in MySQL and myBatis . I wanted to know if this is the proper way to handle the multi thread with myBatis. Thank's.

1 Answer 1

4

SqlSessionFactory is thread safe. Just pass it around. You are safe to use it.

SqlSession is not thread safe and should be used only in method scope.

I would recommend the DAO pattern to structure your database code:

public MyPojo select(int primaryKey) {
    try (SqlSession session = sqlSessionFactory.openSession()) {
        MyPojoMapper mapper = session.getMapper(MyPojoMapper.class);
        return mapper.select(primaryKey);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.