I have following mappings:
Author:
@Entity
@Getter
@Setter
public class Author {
@Id
@GeneratedValue(strategy = IDENTITY)
@Access(PROPERTY)
private Long id;
}
Book:
@Entity
@Getter
@Setter
public class Book {
@Id
@GeneratedValue(strategy = IDENTITY)
@Access(PROPERTY)
private Long id;
@ManyToOne(fetch = LAZY)
private Author author;
}
Following code demonstrates the issue:
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private EntityManagerFactory emf;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
saveBookAndAuthor();
EntityManager em = emf.createEntityManager();
Book book = em.find(Book.class, 1L);
Author author = book.getAuthor();
System.out.println(author.getClass());
author.toString();
}
private void saveBookAndAuthor() {
EntityManager entityManager = emf.createEntityManager();
entityManager.getTransaction().begin();
Author author = new Author();
Book book = new Book();
book.setAuthor(author);
entityManager.persist(author);
entityManager.persist(book);
entityManager.getTransaction().commit();
entityManager.close();
}
}
Here is a part of logs:
class com.example.demo.Author_$$_jvst5e0_0
2017-11-22 22:12:56.671 DEBUG 9426 --- [ main] org.hibernate.internal.SessionImpl : Initializing proxy: [com.example.demo.Author#1]
2017-11-22 22:12:56.671 DEBUG 9426 --- [ main] org.hibernate.SQL : select author0_.id as id1_0_0_ from author author0_ where author0_.id=?
author.toString(); line causes the Author entity initialization even if the toString() method was not overridden.
Is there a way to avoid it?
Spring boot version: 1.5.8.RELEASE
Hibernate version: 5.0.12.Final