我在这里有以下情况:
广告系列包含许多用户。每个用户由广告系列ID,用户ID和他的分支标识。映射如下:
@Entity
public class Campaign {
@Id
private Integer id;
@OneToMany(mappedBy = "campaign", cascade = ALL)
private Set<UserByCampaign> usersByCampaign;
}
UserByCampaign
类以这种方式定义:
@Entity
public class UserByCampaign {
@EmbeddedId
private UserByCampaignPk id;
@MapsId("userId")
@ManyToOne
@JoinColumn(name = "FK_USER", referencedColumnName = "ID")
private User user;
@MapsId("campaignId")
@ManyToOne
@JoinColumn(name = "FK_CAMPAIGN", referencedColumnName = "ID")
private Campaign campaign;
private String branch;
@Embeddable
public static class UserByCampaignPk implements Serializable {
private Integer userId;
private Integer campaignId;
}
}
还有一个User
类:
@Entity
public class User {
@Id
private Integer id;
@OneToMany(mappedBy = "user")
private Set<UserByCampaign> usersByCampaign;
}
当然,我已经压缩了剩下的代码以缩短代码。 每次我尝试使用一堆User持久化Campaign对象时,它会抛出一个异常,试图插入一个新用户。不用说,异常的堆栈表明违反了用户表的唯一约束。
INFO: Hibernate: select SEQ_CAMPAIGN.nextval from dual
INFO: Hibernate: insert into CAMPAIGN (...)
INFO: Hibernate: insert into USER (STATUS, ID) values (?, ?)
WARN: SQL Error: 1, SQLState: 23000
ERROR: ORA-00001: unique constraint (SYS_C0083506) violated
INFO: HHH000010: On release of batch it still contained JDBC statements
WARNING: DTX5014: Caught exception in beforeCompletion() callback:
删除@MapsId
注释并将@ManyToOne
两个映射设为insertable=false
和updatable=false
,它可以根据需要运行。
我正在使用Java SE8,JavaEE7和Payara4.1运行基于maven的Web应用程序。
修改
我使用Hibernate 4.3运行它,但在更新到5.2.10.Final之后也会发生。