这是我的实体:
public class Account extends AbstractEntity<Long> { @Id @SequenceGenerator(name = "accountSequence",sequenceName = "SQ_ACCOUNTS",allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "accountSequence") @Column(name = "ACC_ID",nullable = false) private Long id; ... } public class Integration extends AbstractEntity<Long> { @Id @SequenceGenerator(name = "integrationSequence",sequenceName="SQ_INTEGRATIONS",generator = "integrationSequence") @Column(name = "INT_ID",nullable = false) private Long id; ... public void addIntegration(Integration integration) { IntegrationAccount association = new IntegrationAccount(); // This does not help //association.setIntAccountsPK(new IntAccountsPK(integration.getId(),this.getId())); association.setAccount(this); association.setIntegration(integration); this.integrationAccounts.add(association); integration.getIntAccountsCollection().add(association); } }
这是连接表的实体
@Entity @Table(name = "INT_ACCOUNTS") public class IntegrationAccount { @EmbeddedId protected IntAccountsPK intAccountsPK; @JoinColumn(name = "ACC_ID",referencedColumnName = "ACC_ID",insertable = false,updatable = false) @ManyToOne private Account account; @JoinColumn(name = "INT_ID",referencedColumnName = "INT_ID",updatable = false) @ManyToOne private Integration integration; ... } @Embeddable public class IntAccountsPK implements Serializable { @Column(name = "INT_ID",nullable = false) private Long intId; @Column(name = "ACC_ID",nullable = false) private Long accId; ... }
当我这样做时:
account.addIntegrations(integrations.getTarget()); account.setCustomer(customer); accountService.save(account);
我在日志中得到了这个
引起:org.hibernate.id.IdentifierGenerationException:为以下项生成的null id:class com.dhl.dcc.domain.IntegrationAccount
我对这种映射没有太多的了解,请你告诉我如何改进这种映射(必须保留连接表的实体)以及如何使用相关的集成来保存帐户?谢谢.
解决方法
您可以为IntegrationAccount创建ID字段,然后为两个字段创建唯一约束.
@Entity @Table(name = "INT_ACCOUNTS",uniqueConstraints=@UniqueConstraint(columnNames={"ACC_ID","INT_ID"})) public class IntegrationAccount { @Id private Long id; @JoinColumn(name = "ACC_ID",updatable = false) @ManyToOne private Integration integration; ... }
奇迹般有效!