级联类型持续存在多对多关系



我有两个类策略和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>();
}

现在,当我使用级联类型作为持久时,我得到以下错误:

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();
    }

使用 session.persist() 而不是 session.save()

有关明确的详细信息,请参阅休眠文档:

1) Session.persist():

使瞬态实例持久化。此操作级联到 关联的实例(如果关联映射到 级联="持久"

2) Session.save():

保留给定的瞬态实例,首先分配生成的 标识符。(或者使用标识符属性的当前值,如果 使用分配的生成器。此操作级联到关联的 关联映射为 cascade="save-update" 的实例

相关内容

  • 没有找到相关文章

最新更新