我在一个多线程Java应用程序上工作,它是一个提供REST服务的Web服务器,每秒约有1000个请求。我有一个关系数据库,并且使用 hibernate 方式来访问它。该数据库每秒大约有300-400个请求。从多线程的角度来看,我想知道DAO模式是否正确。
因此,有一个BaseModel类看起来像这样:
public class BaseModelDAO
{
protected Session session;
protected final void commit() {
session.getTransaction().commit();
}
protected final void openSession() {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
}
}
然后,我为数据库中的每个表都有一个DAO类:public class ClientDAOHibernate extends BaseModelDAO implements ClientDAO
{
private Logger log = Logger.getLogger(this.getClass());
@Override
public synchronized void addClient(Client client) throws Exception {
try {
openSession();
session.save(client);
commit();
log.debug("client successfully added into database");
} catch (Exception e) {
log.error("error adding new client into database");
throw new Exception("couldn't add client into database");
} finally {
session.close();
}
}
@Override
public synchronized Client getClient(String username, String password) throws Exception {
Client client = null;
try {
openSession();
client = (Client) session.createCriteria(Client.class).createAlias("user", "UserAlias").add(Restrictions.eq("UserAlias.username", username)).add(Restrictions.eq("UserAlias.password", password)).uniqueResult();
commit();
} catch (Exception e) {
log.error("error updating user into database");
throw new DBUsersGetUserException();
} finally {
session.close();
}
return client;
}
}
这是我的问题:最佳答案
不,您的实现不是一个好方法:
关于java - DAO模式多线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11817872/