PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

前端 未结 18 2350
醉酒成梦
醉酒成梦 2020-11-22 05:10

I have a JPA-persisted object model that contains a many-to-one relationship: an Account has many Transactions. A Transaction has one

18条回答
  •  孤街浪徒
    2020-11-22 05:32

    Even if your annotations are declared correctly to properly manage the one-to-many relationship you may still encounter this precise exception. When adding a new child object, Transaction, to an attached data model you'll need to manage the primary key value - unless you're not supposed to. If you supply a primary key value for a child entity declared as follows before calling persist(T), you'll encounter this exception.

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

    In this case, the annotations are declaring that the database will manage the generation of the entity's primary key values upon insertion. Providing one yourself (such as through the Id's setter) causes this exception.

    Alternatively, but effectively the same, this annotation declaration results in the same exception:

    @Entity
    public class Transaction {
        @Id
        @org.hibernate.annotations.GenericGenerator(name="system-uuid", strategy="uuid")
        @GeneratedValue(generator="system-uuid")
        private Long id;
    ....
    

    So, don't set the id value in your application code when it's already being managed.

提交回复
热议问题