Best practices to write an Entity in Spring/Hibernate
- Every entity has to have a public default contstructor
fetchType = FetchType.LAZYon@OneToOne,@OneToManyand@ManyToOneand other associations (EAGER is the default except@OneToMany)- If an association is not mandatory:
optional = falseon association annotations@Columnand@JoinColumnshould containnullable = false
- Entity should implement
Persistable<IDTYPE>interface- Create own interface with default implementation:
public interface Identifiable extends Persistable<Long> {
default isNew() {
return getId() == null;
}
}
- All ids should be boxed like
Long,Integer,String, etc. (ImplementingPersistable<IDTYPE>will ensure this.) - Do not use lombok for entities (hibernate), generated code interfere with each other
- Do not reimplement
equalsandhashCodefor entities - Do not use primitives if they can be null in the DB
In the service layer:
- Use
@Transactional(readOnly = true)if the method can write db or@Transactional(readOnly = false)if not (false is the default in spring)