Is there any way to generate long type custom id as primary key in hibernate? I have read this hibernate ID but it is working when the type of Id is String. My desired id look like "yyyymm00001" ex:20180900001; Here the below method is returning my desired format but in String type. How can I make it as a long type?
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
Serializable result = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
String month= String.format("%02d",Calendar.getInstance().get(Calendar.MONTH)+1);
try {
connection = session.connection();
statement = connection.createStatement();
try {
statement.executeUpdate("UPDATE " + DEFAULT_SEQUENCE_NAME + " SET next_val=LAST_INSERT_ID(next_val+1)");
resultSet = statement.executeQuery("SELECT next_val FROM " + DEFAULT_SEQUENCE_NAME);
} catch (Exception e) {
System.out.println("In catch, cause : Table is not available.");
statement.executeUpdate("UPDATE " + DEFAULT_SEQUENCE_NAME + " SET next_val=LAST_INSERT_ID(next_val+1)");
resultSet = statement.executeQuery("SELECT next_val FROM " + DEFAULT_SEQUENCE_NAME);
}
if (resultSet.next()) {
int nextValue = resultSet.getInt(1);
String suffix = String.format("%05d", nextValue);
result = year.concat(month).concat(suffix);
System.out.println("Custom generated sequence is : " + result);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}