【发布时间】:2015-10-17 04:30:39
【问题描述】:
我正在创建一个使用 hibernate 作为持久层的 CRUD API。
API 采用 JSON 并将其序列化为 POJO。然后管理层将 POJO 转换为新的 Hibernate Domain 对象。
Create 和 Update 运行完全相同的代码 - 唯一的区别是,对于 Update,我还设置了休眠对象的 ID 字段。
创建工作正常,但更新失败并显示org.hibernate.exception.LockTimeoutException。经过几个小时的窥探,我将挥舞白旗,希望有人能解释我是白痴的所有原因。
ClientManager 代码
public class ClientManager {
private static final ClientDAO clientDAO = new ClientDAO();
...
public Client updateClient(ClientVO inputVO) {
// Generate a Client from the input
Client client = ClientManager.generateClient(inputVO);
client.setClientKey(Integer.parseInt(inputVO.getPersonalId()));
client.setUpdateDate(new Date());
client.setUpdateTimestamp(new Date());
// Update the client
clientDAO.update(client);
}
...
public static Client generateClient(ClientVO clientVO) {
Client client = new Client();
client.setFirstName(clientVO.getFirstName());
client.setMiddleName(clientVO.getMiddleName());
client.setLastName(clientVO.getLastName());
return client;
}
}
BaseDAO 代码(ClientDAO 扩展 BaseDAO)
public class BaseDAO {
public Boolean save(Object object) {
Session session = getSession();
Transaction tx = session.beginTransaction();
session.save(object);
tx.commit();
session.close();
return Boolean.TRUE;
}
public Boolean update(Object object) {
Session session = getSession();
Transaction tx = session.beginTransaction();
session.merge(object);
tx.commit();
session.close();
return Boolean.TRUE;
}
public Session getSession()
{
return HibernateSessionFactory.getSession();
}
}
入口点代码
@PUT
@Path("clients/{personalId}")
@Produces({MediaType.APPLICATION_JSON})
public String updateClient(@PathParam("personalId") String personalId, String data) throws JsonParseException, JsonMappingException, IOException {
ClientVO inputVO = om.readValue(data, ClientVO.class);
inputVO.setPersonalId(personalId);
ClientVO outputVO = clientManager.updateClient(inputVO);
return om.writeValueAsString(outputVO);
}
注意clientKey是主键。
超时发生在 BaseDAO 的 update() 方法中的 .commit() 处。
如果有用的话,我很乐意提供更多代码(例如 ClientVO)。
【问题讨论】:
标签: java hibernate orm concurrency transactions