Hi! I need help. I'm just starting to learn hibernate.
Used DBMS - MySQL.
This code reads an entry from view "FreeGroup" and writes the value in the table "BlockedGroup". Several threads have simultaneous access to this code.
What can i do to lock in the reading of "FreeGroup" and at the same time lock in the writing table "BlockedGroup"?
Code:
public Long addBlockedGroup() throws SQLException {
Long groupId = (long) -1;
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<FreeGroup> freeGroups = new ArrayList<FreeGroup>();
freeGroups = session.createQuery("SELECT i FROM FreeGroup i").setLockMode("i", LockMode.READ).list();
session.createCriteria(FreeGroup.class).setMaxResults(1).list();
if (freeGroups.size() != 0) {
groupId = freeGroups.get(0).getGroupId();
BlockedGroup blockedGroup = new BlockedGroup(groupId);
session.save(blockedGroup);
}
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("AddBlockedGroup failed: " + e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
return groupId;
}
}