DAO-like class shared in static field - is it thread-safe approach?

16 views
Skip to first unread message

Libor Jelínek

unread,
Jun 17, 2012, 5:22:42 AM6/17/12
to mybatis-user
Hello all MyBatis fellows,
it's more general Java question rather then MyBatis related, yet let
me to ask here.

I have DAO-like class looking like this excerpt:

public class FileDao {
public void insertFile(long id) {
SqlSession session =
SystemInstanceFactory.getInstance().getSqlSessionFactory().openSession();

try {
session.getMapper(FileMapper.class).insertFile(id)
session.commit();

} finally {
session.close();
}
}
// ...
}

Is it thread-safe to create and share instance of FileDao in static
field of client class like in this example:

public class FileImpl implements IFile {
private static final FileDao fileDao = new FileDao();

// used in the rest of class as:
public void create(long id) {
fileDao.insertFile(id);
}
}

Class FileImpl will be used in multi-threaded environment.

Thank you for your clarification!
Libor

Eduardo Macarron

unread,
Jun 17, 2012, 6:09:53 AM6/17/12
to mybati...@googlegroups.com
Yes, no problem with that. The dao is a singleton but there is a
different session per thread so that is fine.

2012/6/17 Libor Jelínek <ljel...@virtage.com>:
Reply all
Reply to author
Forward
0 new messages