@EmbeddedId with autogenerated id using @GenerateValue, this mix doesn't works as needed

假如想象 提交于 2019-12-10 19:54:16

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15701576/embeddedid-with-autogenerated-id-using-generatevalue-this-mix-doesnt-works-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!