Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the @PrePersist annotation to generate an ID if it doesn't already have one. I was surprised by your comment that it couldn't be done with interceptors or event listeners, so I decided to try it out. </p> <p>Here's an example of how to do it. I have a class "Test" that has a manually assigned id and then I implemented a @PrePersist method to assign the ID to the hashCode() value if it doesn't already have an ID. You can substitute whatever generation scheme you want in place of the hashCode() call.</p> <pre><code>@Entity @Table (name="Test") public class Test{ @Id @Column(name="id") private String id; @Column(name="PROPERTY") private String property; public Test() { } ... // Other constructors, getters and setters @PrePersist void generateId() { if (id == null) { id = Integer.toHexString(hashCode()); } } </code></pre> <p>I tested out both assigned and unassigned ids with both creating new entities and updating existing entities and didn't run into any issues.</p> <p>Example of creating new entity:</p> <pre><code>Test assigned = new Test("assigned", "p1"); Test generate = new Test(); generate.setProperty("p2"); manager.persist(assigned); manager.persist(generate); manager.getTransaction().commit(); </code></pre> <p>Example of updating existing entity:</p> <pre><code>Test update = manager.find(Test.class, "assigned"); actionUpdate.setProperty("imageUpdated"); Test update2 = manager.find(Test.class, "some-generated-id"); update2.setProperty("videoUpdated"); manager.getTransaction().commit(); </code></pre> <p>Hope this helps.</p> <p>Sarah</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload