I have an entity structure:
@Entity
@Table(name = "Book")
public class Book {
@Id
@Access(AccessType.PROPERTY)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "AUT_ID")
@Fetch(FetchMode.JOIN)
private Author author;
Book(){}
public Book(Author author) {
this.author = author;
}
public Long getId() {
return this.id;
}
public Author getAuthor() {
return this.author;
}
}
@Entity
@Table(name = "Author")
public class Author {
@Id
@Access(AccessType.PROPERTY)
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
private List<Book> books;
Author(){}
public Long getId() {
return this.id;
}
public List<Book> getBooks() {
return this.books;
}
}
I have read in other answers that having an @Id
field with @Access(AccessType.PROPERTY)
allows me to do something like:
// BookRepository is just a CrudRepository<Book,Long>
Book book = bookRepository.findById(1L); // Triggers a Select Query
Long authorId = book.getAuthor().getId(); // Does not trigger a query
And only a single query would be made to the DB because the Author ID
is already loaded from the initial select.
When I do this and boot up my Spring Boot app I get:
org.hibernate.PropertyNotFoundException: Could not locate setter method for property [com.demo.repository.persistance.entity.Book#id]
org.hibernate.PropertyNotFoundException: Could not locate setter method for property [com.demo.repository.persistance.entity.Author#id]
This presumably means I need to have a setId
method on my Entities
I would rather not do this as it makes ID
mutable. Is there a way I can get the benefits of Property
Access (i.e that no extra query is made for a getId
on a child object) and keep my ID
s immutable?
If I remove the Access
annotations my SQL log looks like:
DEBUG o.h.SQL:92 - select book0_.id as id1_1_, book0_.aut_id as aut_id2_1_ from book book0_ where book0_id=?
TRACE o.h.t.d.s.BasicBinder:65 - binding parameter [1] as [BIGINT] - [1]
DEBUG o.h.SQL:92 - select author0_.id as id1_0_0_ from author author0_ where author0_.id=?
TRACE o.h.t.d.s.BasicBinder:65 - binding parameter [1] as [BIGINT] - [1]