Reputation: 43
I am trying to insert a record in Employee table with Hibernate ORM but keep getting an error as :
org.hibernate.AssertionFailure: null id in
com.example.helloworld.entities.Employee entry (don't flush the Session
after an exception occurs)
If I pass ID value then it works fine but although I have used @GeneratedValue(strategy = GenerationType.IDENTITY)
it does not generate 'id'
automatically. Any help is appreciated! Details on DB schema and entity code is as given below.
DB Engine: Postgres
ORM : Hibernate
I have following two tables :
Table Name Employee:
Column Name | Type | Length | Not Null | Default
name | Varchar | 64 | true | NULL
id | int8 | 19 | true |nextval(Employee_id::regclass)
company_id | int8 |19 | true | NULL
Table #Company
Column Name | Type | Length | Not Null | Default
Cname | Varchar | 64 | true | NULL
id | int8 | 19 | true | nextval(Company_id::regclass)
area | varchar |64 | true | NULL
Entity Java Classes for above tables :
@Entity
@Table(name = "Employee")
public class Employee {
public Employee() {super();}
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull
private long id;
@NotNull
@Column(name = "company_id")
private long company_id;
@NotNull
@Column(name = "name")
private String name;
@ManyToOne
private Company company;
/**
setters and getters
**/
}
@Entity
@Table(name = "Company")
public class Company {
public Company() {super();}
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull
private long id;
@NotNull
@Column(name = "area")
private String area;
@NotNull
@Column(name = "cname")
private String cname;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="company_id")
private Set<Employee> employees;
/**
setters and getters
**/
}
Upvotes: 0
Views: 1330
Reputation: 43
This is what worked for me :
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY, generator="seq_name_generated_in_db")
@SequenceGenerator(name="seq_name_generated_in_db", sequenceName="seq_name_generated_in_db", initialValue = 1 , allocationSize=1)
Upvotes: 0
Reputation: 1025
I had the same issue with Postgres.
Try adding a SequenceGenerator
to your id
field:
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SEQ_EMPLOYEE")
@SequenceGenerator(name="SEQ_EMPLOYEE", sequenceName="SEQ_EMPLOYEE", allocationSize=1)
@NotNull
private long id;
Replace SEQ_EMPLOYEE
with the name of the sequence in the database.
Upvotes: 1