Hello DB/Hibernate experts
I'm not sure how to do this in Hibernate, or relational databases in general.
What I need is one of my persistent classes to have only a single instance in the database - a persistent singleton, in other words. I think I need to use pessimistic locking somehow...
I have the following mapping document:
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="com.gfg.pcm.riskalerts.domain">
<class name="AuthsNextNumber" >
<id name="id" type="int" unsaved-value="0">
<generator class="assigned" />
</id>
<property name="nextId" type="java.lang.Long" not-null="true" />
</class>
</hibernate-mapping>
I'm trying to use the DB to store the next number in a batch. So I want a table with a single record, the ID can just be 1. I want to check if it exists, and if not, create it. But obviously I don't want some concurrent process to create an instance if it also finds that it doesn't exist.
I'm thinking along the lines of:
Code:
AuthsNextNumber nextNumber = (AuthsNextNumber)
session.get(AuthsNextNumber.class, new Integer(1), LockMode.UPGRADE);
if (nextNumber == null)
{
nextNumber = new AuthsNextNumber(1);
session.save(nextNumber);
}
else
{
// Update nextNumber, etc.
session.update(nextNumber);
}
but, I suspect this won't work. How should I do this?
Any help much appreciated...
Craig