2

JSR 338: JavaTM Persistence API 2.1 Specification > 2.1 The Entity Class specifies:

The entity class must not be final. No methods or persistent instance variables of the entity class may be final.

So I tried with Hibernate 5.2.18.Final to prove it by setting an entity class as final:

@EqualsAndHashCode
@Getter
@Setter
@Entity
public final class City {
    @Id
    @SequenceGenerator(name="city_sequence", sequenceName="city_seq", initialValue=0, allocationSize=25)
    @GeneratedValue(strategy=SEQUENCE, generator="city_sequence")
    private int id;
    @Column(length=20, nullable=false)
    private String city;
    @ManyToOne(fetch = FetchType.LAZY)
    private Province province;
}

However, the result is out of my expectation: the corresponding table can be generated and new instance of City can be persisted to the database, meaning my code proves that entity class can be final

Question: Is there any better way to prove the entity class must not be final? Isn't it a hard-and-fast rule as it is in the specification?

Rui
  • 3,454
  • 6
  • 37
  • 70
  • 1
    https://javarevisited.blogspot.com/2016/01/why-jpa-entity-or-hibernate-persistence-should-not-be-final-in-java.html , https://docs.jboss.org/hibernate/orm/5.0/mappingGuide/en-US/html/ch02.html - amazing what the internet contains. – user2864740 Jan 19 '20 at 04:22
  • Note that Hibernate is a JPA *implementation* and thus may have implementation-specific behavior or allowances not in strict conformance of (or as limited as) the formal specification in all cases. Or: “the devil is in the details”. – user2864740 Jan 19 '20 at 04:25
  • (So the only “proof” is that the JPA specifications says the class cannot be final.) – user2864740 Jan 19 '20 at 04:43
  • Thanks really much for your comment, esp. the link to Hibernate 5 guide. So the more persuasive proof might be using the dynamic proxy for lazy load with Hibernate? I could try that. In the same time I learn dynamic proxy pattern – Rui Jan 19 '20 at 04:46

0 Answers0