org.hibernate.PersistentObjectException: detached entity passed to persist exception

前端 未结 4 1717
遇见更好的自我
遇见更好的自我 2021-02-13 01:23

I\'m creating a simple app to just insert a row to a table (if table does not exist, create it) using Java JPA.

I\'m attaching some code for a runnable exam

相关标签:
4条回答
  • 2021-02-13 02:08

    You can use this contrustor like this:

    Person p = new Person(0, "Peter", "Parker");
    

    then when JPA persist to database it'll automatically insert with AUTO_INCREMENT strategy.

    0 讨论(0)
  • 2021-02-13 02:23

    The reason for this is that you have declared the id in Person class as generated with auto strategy meaning JPA tries to insert the id itself while persisting the entity. However in your constructor you are manually setting the id variable . Since the ID is manually assigned, and that the entity is not present in the persistence context this causes JPA to think that you are trying to persist an entity which is detached from persistence context and hence the exception.

    To fix it dont set the id in the constructor.

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    
    
    
    public Person(int id, String name, String lastName) {
           // this.id = id;
            this.name = name;
            this.lastName = lastName;
      }
    
    0 讨论(0)
  • 2021-02-13 02:24

    In the class definition you have annotated id to be generated by strategy (table, sequence, etc.) chosen by the persistence provider, but you are initializing the id of the Person object through constructor. I think leaving id null may solve your problem.

    0 讨论(0)
  • 2021-02-13 02:26

    Try with the below code then, it will allow you to set the ID manually.

    Just use the @Id annotation which lets you define which property is the identifier of your entity. You don't need to use the @GeneratedValue annotation if you do not want hibernate to generate this property for you.

    assigned - lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.

    package view;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "People")
    public class Person {
        @Id
        //@GeneratedValue(strategy = GenerationType.AUTO) // commented for manually set the id
        private int id;
    
        private String name;
        private String lastName;
    
        public Person(int id, String name, String lastName) {
            this.id = id;
            this.name = name;
            this.lastName = lastName;
        }
    
        public Person() {
        }
    }
    
    0 讨论(0)
提交回复
热议问题