I am trying to work with @EmbeddedId, this is my code as follows,
create table TBL_EMPLOYEE_002(
ID integer generated always as identity (start with 100,increment by 10),
COUNTRY varchar(50),
NAME varchar(50),
constraint PK_EMP_00240 primary key(ID,COUNTRY)
)
The Embedded class as follows,
@Embeddable
public class EmployeeIdTwo implements Serializable{
public EmployeeIdTwo(){}
public EmployeeIdTwo(String country){
this.empCountry = country;
}
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")
private Integer employeeId;
@Column(name="COUNTRY",length=50)
private String empCountry;
// implementation of hashCode and equals and only getters
...
}
employee Entity as follows,
@Entity
@Table(name="TBL_EMPLOYEE_002")
public class EmployeeEntitySix implements Serializable{
public EmployeeEntitySix(){}
public EmployeeEntitySix(EmployeeIdTwo id,String name){
this.id = id;
this.employeeName = name;
}
@EmbeddedId
private EmployeeIdTwo id;
@Column(name="NAME")
private String employeeName;
// getters and setters
}
this is the code written in main method,
private static void storVal(EntityManager em){
EmployeeEntitySix employee = new EmployeeEntitySix(new EmployeeIdTwo("KENYA"), "Henry Olaanga");
em.persist(employee);
}
but once i run an above code i get an exception as follows,
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Attempt to modify an identity column 'ID'.
Can you please let me know where i am getting wrong, if my EmbeddedId class contain an autogenerated column, than what should be the approach.
Just to know I am using hibernate as persistence provider and JPA as persistence API
I'm assuming you would not be asking this question if Id
could easily and uniquely identify an employee. If you have the ability to modify your tables, I'd suggest either making Id
reliably unique, or adding an auto-generated UniqueId
column.
Some of these kinds of errors actually come from the DB schema, and not from JPA/Hibernate. If you're trying to update a column that the DB doesn't have a generation strategy for, this might be what is causing your error.
You might also have a look at autoincrement id is not reflecting in composite key using JPA, as I think this covers what you are asking about.