我有两个类 Policy 和 Acl。他们有一个多对多的关系。
// 政策
public class PolicyEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "POLICY_ID")
private int policyId;
@Column(name = "POLICY_NAME")
private String policyName;
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "POLICY_ACL",joinColumns=@JoinColumn(name = "POLICY_ID"),
inverseJoinColumns=@JoinColumn(name = "ACL_ID"))
private List<AclEntity> aclList = new ArrayList<AclEntity>();
}
// Acl
public class AclEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ACL_ID")
private int aclId;
@Column(name = "ACL_NAME")
private String aclName;
@ManyToMany(mappedBy = "aclList")
private List<PolicyEntity> policyList = new ArrayList<PolicyEntity>();
}
现在,当我使用 Cascade 类型作为 persist 时,我收到以下错误:
Hibernate: insert into POLICY (POLICY_NAME, POLICY_ID) values (?, ?)
Hibernate: insert into POLICY_ACL (POLICY_ID, ACL_ID) values (?, ?)
Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: hibernate.AclEntity
而当我全部使用级联类型时,它会成功保存策略实体和 acl 实体。我无法理解这是如何发生的。注意:我只是在执行保存操作。
这是主要代码:
public static void main(String[] args) {
PolicyEntity policyEntity = new PolicyEntity();
AclEntity aclEntity = new AclEntity();
//policyEntity.setPolicyId(1);
policyEntity.setPolicyName("Policy 3");
//aclEntity.setAclId(1);
aclEntity.setAclName("Acl 3");
policyEntity.getAclList().add(aclEntity);
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(policyEntity);
session.getTransaction().commit();
session.close();
}