Hibernate check if entity has changed

时间:2019-01-18 18:59:38

标签: java hibernate

I have two applications - Server that has connection with database and Client which doesn't. Server loads entity and sends it to Client. Client edits it and sends it back so that Server can update it. But... there are many Clients and many of them can edit that entity and want to update it with their own value but I want Server to update it only if it hasn't been updated since it had been send to Client. Namely: Clients try to set ticket's status to their own value but only if current status in database is the same that it was when that Client received it. Currently I have it like that:

public boolean changeStatus (Ticket ticket, short newStatus) {
    short previousStatus = ticket.getStatus();
    boolean result = false;
    Session session = sessionFactory.openSession();
    Transaction tx = null;

    try {
        tx = session.beginTransaction();

        String sql = "UPDATE ticket SET status = :newStatus WHERE idTicket = :idTicket AND status = :previousStatus";
        NativeQuery query = session.createSQLQuery(sql);

        query.setParameter("idTicket", ticket.getIdTicket());
        query.setParameter("newStatus", newStatus);
        query.setParameter("previousStatus", previousStatus);
        result = query.executeUpdate() == 1;

but sometimes I also want to set other atributes and check if other atributes hasn't changed and using that method would make it very ugly and I want it to be more object-oriented not plain sql. Any suggestions?

Forgot to mention that each Client has it's own Server thread that might try to update

0 个答案:

没有答案