0

I tried many time to insert id value in my table using below code, but it always throwing org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.app.entites.LDetails

following is the code in entity class

@Column(name="LID")
@GenericGenerator(name="generatedId", strategy="com.app.common.IdGenerator")
@GeneratedValue(generator="generatedId", strategy=GenerationType.SEQUENCE)
@NotNull
private String lId;

i have implemented id generator using IdentifierGenerator as below

public class IdGenerator implements IdentifierGenerator{

private static String id;

@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
    Connection con = session.connection();
    try {
        Statement statement = con.createStatement();
        ResultSet rs = statement.executeQuery("select count(ID) from L_DETAILS");
        if(rs.next()) {
            int i = rs.getInt(1)+1;
            this.id="ll"+i;
            System.out.println("generated id is "+id);
            return "l"+i;
        }
    }catch(SQLException e) {
        e.printStackTrace();
    }
    return null;
}

}

Alexander Petrov
  • 9,204
  • 31
  • 70
  • please check into https://stackoverflow.com/questions/10997494/ids-for-this-class-must-be-manually-assigned-before-calling-save – Ponni Feb 11 '19 at 07:14

2 Answers2

0

Use the following approach for Auto-Id generation of Primary key in your entity class :-

 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.Entity;

        @Entity
        @Table(name = "your_table_name")
        public class YourEntityClass{

            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            @Column(name = "id")
            private long id;

            //other column names

           // setter & getter methods

        }

After this, whenever you're saving a new record in your table you don't have to generate a new id

Sumit
  • 917
  • 1
  • 7
  • 18
0

You have forgotten to add the @Id annotation on top. The fact you have added the @GeneratedValue annotation does not mean you can spare the @Id annotation. You still need it.

Alexander Petrov
  • 9,204
  • 31
  • 70
  • Thank u, but I resolved it, it's not problem with the above. I tried to insert compound key in normal insertion which is wrong! I have to use embeddable annotation on compound key generator class... Anyway thanks Buddy! – Tharun Masarp Feb 12 '19 at 09:45