Java – JPA best practice: statically finding entities
Imagine that an event entity references a state entity:
@Entity @Table(name = "event") public class Event() { @Id @Column(name = "id",nullable = false) private long id; ... @ManyToOne @JoinColumn(name = "status_code",nullable = false) private Status status; } @Entity @Table(name = "status") public class Status() { @Id @Column(name = "code",nullable = false) private String code; @Column(name = "label",nullable = false,updatable = false) private String label; }
The state is mapped to a small table 'state' Status is a typical reference data / lookup entity
code label ----- -------------- CRD Created ITD Initiated PSD Paused CCD Cancelled ABD Aborted
I don't know if modeling a state as an entity is a good idea It feels more like an enumeration of constants
By mapping states to entities, I can use state objects in Java code, and state values also exist in the database This is good for the report
On the other hand, if I want to set a specific state for an event, I can't simply assign the constant state I remember I must first find the correct entity:
event.setStatus(entityManager.find(Status.class,"CRD"))
Can I avoid the above code snippets? I'm afraid of a performance punishment. It looks heavy
>Do I have to adjust things with read-only attributes? > Can I prefetch these lookup entities and use them as constants? > Did I miss the key JPA features? >?
All comments / suggestions / suggestions are welcome!
thank you! J.
Solution
Then you can use an enumeration I really don't understand why you're not practical
However, if you really want to use an entity, it will be the perfect candidate for L2 caching, which will solve your performance problem