gita wrote:
Hi,
How to execute queries like select sequence.nextval from dual into hibernate?
Thanks
gita
I don't know if it is correct way, but in Java code I use net.sf.hibernate.id.SequenceGenerator:
Code:
/* SequenceGenerator is not serializable, let it be transient with lazy initialization */
transient private SequenceGenerator codeNumberSeqGenerator = null;
private NumberFormat codeNumberFormat = null;
private String generateCodeNumber(Request request)
{
String result = null;
try
{
Session session = HibernateUtil.getInstance().currentSession();
/* lazy initialization */
if (null == codeNumberSeqGenerator)
{
codeNumberSeqGenerator = new SequenceGenerator();
Dialect dialect = Dialect.getDialect(HibernateUtil.getInstance().getProperties());
Properties props = new Properties();
props.put("sequence", ""sq_RequestNumber""); // put your sequence name here
codeNumberSeqGenerator.configure(Hibernate.LONG, props, dialect);
codeNumberFormat = NumberFormat.getIntegerInstance();
codeNumberFormat.setGroupingUsed(false);
codeNumberFormat.setMinimumIntegerDigits(4);
codeNumberFormat.setMaximumIntegerDigits(4);
}
assert (null != codeNumberSeqGenerator);
assert (null != codeNumberFormat);
// all the magic is here :)
final Long tmp = (Long) codeNumberSeqGenerator.generate((SessionImpl) session, request);
// format Long result to String according to business reguirements
result = codeNumberFormat.format(tmp);
assert (result.length() == 4);
}
catch (SQLException e)
{
log.error("generateCodeNumber: ", e);
result = null;
}
catch (HibernateException e)
{
log.error("generateCodeNumber: ", e);
result = null;
}
finally
{
Silencer.closeHibernateSession();
if (null == result)
result = "error";
}
return result;
}