Access Strategies in JPA and Hibernate
Access Strategies in JPA and Hibernate
@Entity
public class Review {
@Id
protected Long id;
…
}
www.thoughts-on-java.org
Access Strategies in JPA and Hibernate
@Entity
public class Review {
@Id
public Long getId() {
return id;
}
…
}
@Version
@Access(AccessType.FIELD)
private int version;
@Id
public Long getId() {
return id;
}
…
}
www.thoughts-on-java.org
Access Strategies in JPA and Hibernate
5 reasons why you should use field-based access
As explained earlier, you most often specify your access strategy by
annotating the attributes or getter methods of your entity. But which
strategy should you choose? Does it make a real difference?
Yes, it does make a difference. I always recommend using field-based
access. Here are 5 reasons why field-based access is the better
access strategy.
You can also provide utility methods that enable you to add or
remove elements from a to-many association and prevent direct
access to the underlying List or Set. This makes the implementation
of your business code more comfortable and is a general best
practice for bi-directional many-to-many associations.
www.thoughts-on-java.org
Access Strategies in JPA and Hibernate
@Entity
public class Book {
@ManyToMany
Set<Author> authors;
…
}
www.thoughts-on-java.org
Access Strategies in JPA and Hibernate
@Entity
public class Book {
@ManyToOne
Publisher publisher;
…
}
www.thoughts-on-java.org
Access Strategies in JPA and Hibernate
the case if you use the proxy object in your business code. But quite a
lot of equals and hashCode implementations access the attributes
directly. If this is the first time you access any of the proxy attributes,
these attributes are still uninitialized.
@Entity
public class Book {
@NaturalId
String isbn;
...
@Override
public int hashCode() {
return Objects.hashCode(isbn);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
return Objects.equals(isbn, other.isbn);
}
}
You can easily avoid this pitfall by using the field-based access
strategy.
www.thoughts-on-java.org