Spring-Hibernate1
6. Fetch Types: Eager vs Lazy Loading
Eager will retrieve everything
Lazy will retrieve on request
Mapping
Default Fetch Type
@OneToOne
FetchType.EAGER
@OneToMany
FetchType.LAZY
@ManyToOne
FetchType.EAGER
@ManyToMany
FetchType.LAZY
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@Component
annotation 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:
@ComponentpublicclassEmployeeDAOImplimplementsEmployeeDAO {...}
2) Although above use of@Component
is good enough but you can use more suitable annotation that provides additional benefits specifically for DAOs i.e.@Repository
annotation. The@Repository
annotation is a specialization of the@Component
annotation 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@Service
annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the@Component
annotation, but it’s a good idea to use@Service
over@Component
in service-layer classes becauseit specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.
4)@Controller
annotation marks a class as a Spring Web MVC controller. It too is a@Component
specialization, so beans marked with it are automatically imported into the DI container. When you add the@Controller
annotation 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
Was this helpful?