Hello!
I'm new to Hibernate and try to write my own id generator based on IdentifierGenerator. I need an id of type String, but unfortunately MySQL does not support "nextval". So I try to do a SELECT first, increment my simulated sequence number and then put it back with an UPDATE query.
I want to use transactions for these two queries, but I don't know how. I have done a SELECT with entity manager and em.createQuery before, but I don't know how to UPDATE and do transactions in IdentifierGenerator. Do I have to work with this "SessionImplementor session" object or can I create my own entity manager as usual?
My code is based on this snippet:
http://snipt.net/belano/custom-hibernat ... r-id-fieldCode is still work in progress...
Code:
public class MyGenerator implements IdentifierGenerator
{
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException
{
String prefix = "id-";
int id = 0;
// Is this the right way or do I have to use session argument somehow?
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try
{
Query selectQuery = em.createQuery("SELECT counter AS next_value FROM sequence_numbers WHERE sequence='my_id'");
List<Integer> idList = (List<Integer>)selectQuery.getResultList(); // should work up to here
if (idList.isEmpty())
{
id = 0;
}
else
{
id = idList.get(0) + 1;
}
Query updateQuery = em.createQuery("UPDATE sequence_numbers SET counter=" + id + " WHERE sequence='my_id'");
// how do I send UPDATE query?
String code = prefix + StringUtils.leftPad("" + id, 27, '0');
return code;
// end transaction, close em and emf, end try..catch and so on
}
}
I would appreciate any help, since I'm not very familiar with Hibernate internals yet.
Tnx.