1

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

1 回答 1

3

使用session.persist()代替session.save()

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

1)会话.persist():

使瞬态实例持久化。如果关联映射为 cascade="persist" ,则此操作级联到关联实例

2)会话.save():

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

于 2015-04-29T12:37:36.717 回答