java.lang.IllegalStateException:事务未激活

时间:2015-05-16 07:29:36

标签: hibernate jpa

java.lang.IllegalStateException:org.hibernate.TransientPropertyValueException:object引用未保存的瞬态实例 - 在刷新之前保存瞬态实例:entity.Customer.passport - > entity.Passport

尝试使用hybernate持续时出现此错误。 以下是我的客户实体 calss

package entity;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @OneToOne(cascade = { CascadeType.MERGE })
    @JoinColumn(name = "passport_id", unique = true)
    private Passport passport;

    public Customer() {
    }

    public Customer(String name, Passport passport) {
        this.setName(name);
        this.passport = passport;
    }

    public Passport getPassport() {
        return passport;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

以下是我创建实体管理器工厂内容的主要方法。

 package client;

    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;

    import entity.Customer;
    import entity.Passport;

    public class OneToOneClient {

        public static void main(String[] args) {
            EntityManagerFactory emf = Persistence
                    .createEntityManagerFactory("jpa-training");
            EntityManager em = emf.createEntityManager();
            EntityTransaction txn = em.getTransaction();
            try {
                em.getTransaction().begin();
                //txn.begin();

                Passport passport = new Passport("99627317");
                Customer customer = new Customer("Customer1", passport);
                em.persist(customer);

                em.getTransaction().commit();
                //txn.commit();
            } catch (Exception e) {
                if (txn != null) {
                    txn.rollback();
                }
                e.printStackTrace();
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }

    }

注意:如果我在我的实体类中使用 CascadeType.PERSIST ,我可以在数据库中插入另一行。

1 个答案:

答案 0 :(得分:2)

passport保存在客户面前,你没事。您提到的替代方法是使用Cascade.PERSIST

如果没有被告知,Hibernate不会持久存在其他实体。