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
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;
}