0

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;
    }
Aritra Paul
  • 834
  • 1
  • 8
  • 14

1 Answers1

1

to correct this problem, you must add in entity this annotations and make a Long or Integer type for @Id

@Id
@Column(name = Contact.ENCOIDFSYS)
@GeneratedValue(generator = IdfsysGeneratorDefinition.NAME)
@GenericGenerator(name = IdfsysGeneratorDefinition.NAME, strategy = IdfsysGeneratorDefinition.CLASS_NAME, parameters = {  })
private Integer id;

knowing that

public static final String CLASS_NAME = "com.sybaway.generators.hibernate.HibernateIdfsysGenerator";
public static final String NAME = "idfsysGenerator";

And in hibernate generator class, Add this conversion to Long

result = Long.parseLong(year.concat(month).concat(suffix));

instead of :

result = year.concat(month).concat(suffix);

Let me know if all is well