quiqua
01/08/2022, 2:43 PMCREATE TABLE elements (
id SERIAL PRIMARY KEY,
resource_id VARCHAR(50) UNIQUE DEFAULT uuid_generate_v4(),
name VARCHAR(100) NOT NULL
)
and a class like
@Entity
@Table(name = "elements")
data class Element(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
var id: Int?,
@Column
var resourceId: String?,
@Column
var name: String?
)
How can I only create new objects via val elem = Element(name="foo")
and let the rest be automatically created via JPA/Hibernate
Is that even possible in my case? Do I just need different constructors then?jbnizet
01/08/2022, 9:17 PMvar id: Int? = null, var resourceId: String? = UUID.randomUUID().toString()
?
If you let the database generate the UUID, you’d be forced forced to refresh the entity right after it’s been created in order for Hibernate to know what UUID the database has generated. So why not generate it in Java? That said, you shouldn’t use data classes for JPA entities. Their toString(), hashCode() and equals() implementation are not really adequate, and can even be dangerous if you have associations.quiqua
01/09/2022, 7:56 AM