对于可为空的外键字段,获取“对象引用了未保存的瞬态实例”而不是“外键约束异常”

时间:2019-04-12 10:41:50

标签: jpa kotlin foreign-keys

我有一个实体A,该实体具有可为空的外键字段“ field1”,该字段引用了实体B的主键。如果我提出的发布请求的字段值不存在于实体B中。关键异常相反,我正在获取对象引用的未保存瞬态实例异常。如果将'field1'设置为notnull,则预期会出现外键异常。想知道可为空字段和外键约束之间的关系是什么

尝试过

1)      @ManyToOne(cascade = arrayOf(CascadeType.All))
        @JoinColumn(name ="book",referencedColumnName ="book_id")
        var book: Book? = null,

when I am giving this..instead of checking foreign key constraint, it was trying to add book entity also into DB

2)      @ManyToOne(cascade = arrayOf(CascadeType.All))
        @JoinColumn(name ="book",referencedColumnName ="book_id",nullable=true, insertable=false,updatable=false)
        var book: Book? = null,

3)      @ManyToOne(optional=false,fetch=FetchType.EAGER)
        @JoinColumn(name ="book",referencedColumnName ="book_id")
        var book: Book? = null,

4)      @ManyToOne(optional=false,fetch=FetchType.LAZY)
        @JoinColumn(name ="book",referencedColumnName ="book_id")
        var book: Book? = null,


But whatever I try I am getting the same transientobject exception ..only if the field "book" was given a not null constraint in db, it is throwing foreign key exception.
please find the code
    @Entity
    @Table(name ="student")
    class Student(

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    var id: Long? = -1,

    @ManyToOne()
    @JoinColumn(name ="book",referencedColumnName ="book_id")
    var book: Book? = null,
        )


    @Entity
    @Table(name ="book")
    class Book(

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "book_id")
    var book_id: Long? = -1

    )

期望: “无法执行语句; SQL [n / a];约束[书];嵌套异常是org.hibernate.exception.ConstraintViolationException:无法执行语句”

实际得到: “ org.hibernate.TransientPropertyValueException:非null属性引用了一个瞬态值-必须在当前操作之前保存瞬态实例:Student.book-> Book;嵌套异常是java.lang.IllegalStateException:org.hibernate.TransientPropertyValueException:Not-null属性引用了一个瞬态值-瞬态实例必须在当前操作之前保存:Student.book-> Book

0 个答案:

没有答案