我有两个类策略和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类型作为持久性时,我收到以下错误:
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
当我使用cascade类型作为all时,它会成功保存策略实体和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();
}
答案 0 :(得分:3)
使用session.persist()
代替session.save()
有关详细信息,请参阅hibernate文档:
使瞬态实例持久化。此操作级联到 关联映射的关联实例 的级联=&#34;坚持&#34; 强>
保留给定的瞬态实例,首先分配生成的 标识符。 (或者使用标识符属性的当前值if 使用指定的生成器。)此操作级联到关联 实例,如果关联映射为 cascade =&#34; save-update&#34;