Spring-Hibernate1

6. Fetch Types: Eager vs Lazy Loading

  • Eager will retrieve everything

  • Lazy will retrieve on request

@OneToMany(fetch=FetchType.LAZY, mappedBy="instructor")
private List<Course> courses;

Note:

If the Hibernate session is closed, and you attempt to retrieve lazy data Hibernate will throw an exception.

6.1 Retrieve lazy data using

  • option 1: session.get and call appropriate getter method(s)

  • option 2: Hibernate query with HQL

these two are most common.

7 @OneToMany

8. Specialized Annotation for DAOs

@Component, @Repository, @Service and @Controller annotations

1) The@Componentannotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. To use this annotation, apply it over class as below:

2) Although above use of@Componentis good enough but you can use more suitable annotation that provides additional benefits specifically for DAOs i.e.@Repositoryannotation. The@Repositoryannotation is a specialization of the@Componentannotation with similar use and functionality. In addition to importing the DAOs into the DI container,it also makes the unchecked exceptions (thrown from DAO methods) eligible for translationinto SpringDataAccessException.

3) The@Serviceannotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the@Componentannotation, but it’s a good idea to use@Serviceover@Componentin service-layer classes becauseit specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.

4)@Controllerannotation marks a class as a Spring Web MVC controller. It too is a@Componentspecialization, so beans marked with it are automatically imported into the DI container. When you add the@Controllerannotation to a class, you can use another annotation i.e.@RequestMapping; to map URLs to instance methods of a class.

8.1 Spring @Transactional

  • Spring provides an @Transactional annotation

  • Automagically begin and end a transaction for your Hibernate code

    • No need for you to explicitly do this in your code(no need for session.beginTransaction(), session.getTransaction().commit()).

  • This Spring magic happens behind the scenes to handles transaction management.

8.2 @Repository

use for DAO Implementations.

Last updated