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;
}

}

2

There are 2 best solutions below

1
Sumit On

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

1
Alexander Petrov On

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.