我已将实体的 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 创建,则此代码工作正常,但是如果完成此操作后我将属性值更改为“更新”并再次运行相同的代码,我得到以下例外:
javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:无法执行语句
引起原因:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键“PRIMARY”的重复条目“0”
因此,生成的策略在 @Embeddable 对象中不起作用。
这似乎是一个现有的错误 https://bugs.eclipse.org/bugs/show_bug.cgi?id=260983这个问题之前已经解决了。
另外,也发布了类似的问题here https://stackoverflow.com/questions/37448621/embeddedid-with-generatedvalue-in-embeddable
任何帮助或建议表示赞赏。
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)