2

I have separated the id of an entity into a separate @Embeddable class.

The Entity is given below:

@Entity
@Table(name="users")
public class Users {
@EmbeddedId
private Users_pk id;
private String username;
//getters and setters follow

The @Embeddable class is:

@Embeddable
public class Users_pk implements Serializable{
private static final long serialVersionUID = 1L;    
@Column(name="idusers")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//getters and setters follow

I try to persist the users object using the code below:

public class HibernateTest {
public static void main(String[] args) throws SQLException {
Users user = new Users();
user.setId(new Users_pk());
//setting other attributes of user and calling the save method

This code works fine if the "hbm2ddl.auto" property is set to create and the user gets created with id 0, if however after this is done I change the property value to 'update' and run the same code again, I get the below exception:

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '0' for key 'PRIMARY'

So, the Generated strategy is not working in @Embeddable object. This seems to be an existing bug that was resolved earlier. Also, a similar question is posted here

any help or suggestion is appreciated.

Community
  • 1
  • 1

0 Answers0