3

当我org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: safu.Publisher尝试运行以下代码时出现异常:

public class SafuClient {
    public static void main(String[] args) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

            Publisher publisher = new Publisher("ABC", "ABC Co.");
            Book book = new Book("1-932394-88-5", "Safu", publisher);

            session.save(book);        

            session.getTransaction().commit();

    }
}

我有从书到出版商的多对一关系。Book 和 Publisher 实体如下:


@Entity
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)   
    private Long id;
    private String isbn;
    private String name;

    @ManyToOne(cascade={CascadeType.PERSIST})
    @JoinColumn(name="publisher_id")
    private Publisher publisher;    

    public Book() {}
    public Book(String isbn, String name, Publisher publisher) {
        this.isbn = isbn;
        this.name = name;
        this.publisher = publisher;
    }

}

@Entity
public class Publisher {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String code;
    private String name;

    public Publisher() {}
    public Publisher(String code, String name) {
        this.code = code;
        this.name = name;
    }

}

如果我在实体中@ManyToOne(cascade={CascadeType.PERSIST})替换为一切正常。@ManyToOne(cascade={CascadeType.ALL})Book

有人可以解释为什么会这样吗?

4

2 回答 2

1

session.save(book)方法通过从实体中的注释中删除级联属性 ( cascade={CascadeType.PERSIST})并改为添加on publisher 字段来工作。@ManyToOneBook@Cascade (value=CascadeType.SAVE_UPDATE)

使用@Cascade (value=CascadeType.SAVE_UPDATE)Hibernate 的原生注解。


遵循更新的 Book.java 有效:


@Entity
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)   
    private Long id;
    private String isbn;
    private String name;

    @ManyToOne
    @JoinColumn(name="publisher_id")
    @Cascade(value=CascadeType.SAVE_UPDATE)
    private Publisher publisher;    

    public Book() {}
    public Book(String isbn, String name) {
        this.isbn = isbn;
        this.name = name;
    }   
    public Book(String isbn, String name, Publisher publisher) {
        this.isbn = isbn;
        this.name = name;
        this.publisher = publisher;
    }   
}
于 2014-05-07T16:09:32.583 回答
1

试试session.persist(book);这个可以解决问题而不是session.save(book);

于 2014-05-07T15:27:36.210 回答