我已将实体的ID分成单独的@Embeddable类。
实体如下:
@Entity
@Table(name="users")
public class Users {
@EmbeddedId
private Users_pk id;
private String username;
//getters and setters follow
@Embeddable类为:
@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
我尝试使用下面的代码来保留用户对象:
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
如果将“ hbm2ddl.auto”属性设置为创建,并且用户的ID为0,则此代码可以正常工作,但是在完成此操作后,我将该属性值更改为“ update”并再次运行相同的代码,我收到以下异常:
javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:无法执行语句
由以下原因引起:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:密钥“ PRIMARY”的条目“ 0”重复
因此,Generated策略在@Embeddable对象中不起作用。 这似乎是先前已解决的existing bug。 另外,发布了一个类似的问题here
感谢任何帮助或建议。