Reputation: 2658
When I try to persist an entity, the following error occur
org.hibernate.PersistentObjectException: detached entity passed to persist: xxxxxxx.xxxxxxxx.Invoice
My model
@Entity
@Table(name = "invoices")
class Invoice(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = -1,
var date: Date,
@Column(name = "user_id", unique = true)
var userId: Long,
@Column(name = "invoice_number")
var invoiceNumber: String) : Serializable {
constructor(date: Date, userId: Long, invoiceNumber: String) : this(-1, date, userId, invoiceNumber)
}
Invoice object is created as followed
val invoice = Invoice(Date(), 11111, "abc123")
invoiceDao.create(invoice)
In my generic dao I persist
fun create(entity: T): T {
entityManager.persist(entity)
return entity
}
allopen and noarg is included in my build.gradle
Upvotes: 2
Views: 1244
Reputation: 2415
You've defined the id field as auto generated but assigned it a default value. When hibernate tries to persist it, it thinks that the object represents an underlying row in database because it already has an id. So, it considers it a detached object. The persist() method doesn't work on a detached object. You can set the default value of id to null to resolve this issue.
Upvotes: 3