DEV Community

Cover image for Hibernate and Spring JPA Notes
Amit Chaurasia
Amit Chaurasia

Posted on

Hibernate and Spring JPA Notes

1) ORM has the following advantages over JDBC:
Management of transaction.
Generates key automatically.
Details of SQL queries are hidden. Database independent queries.

2) Second level cache is not enabled by default in Hibernate.

3) SessionFactory is a thread-safe object. Hibernate Session is not a thread-safe object and so you must not share Hibernate-managed objects between threads.
4) There are 3 states of the object (instance) in hibernate.
a) Transient: The object is in a transient state if it is just created but has no primary key (identifier) and not associated with a session.
b) Persistent: The object is in a persistent state if a session is open, and you just saved the instance in the database or retrieved the instance from the database.
c) Detached: The object is in a detached state if a session is closed. After detached state, the object comes to persistent state if you call lock() or update() method.

5) There are 3 ways of inheritance mapping in hibernate.
a) Table per hierarchy
b) Table per concrete class
c) Table per subclass

6) What is automatic dirty checking in hibernate?
The automatic dirty checking feature of Hibernate, calls update statement automatically on the objects that are modified in a transaction.
7) There can be 4 types of association mapping in hibernate.
a) One to One
b) One to Many
c) Many to One
d) Many to Many

8) Is it possible to perform collection mapping with One-to-One and Many-to-One?
No, collection mapping can only be performed with One-to-Many and Many-to-Many.

9) What is lazy loading in hibernate?
Lazy loading in hibernate improves the performance. It loads the child objects on demand.
Since Hibernate 3, lazy loading is enabled by default, and you don’t need to do lazy=”true”. It means not to load the child objects when the parent is loaded.

10) What is the difference between first level cache and second level cache?
1) First Level Cache is associated with Session. Second Level Cache is associated with SessionFactory.
2) First Level Cache is enabled by default. Second Level Cache is not enabled by default.

11) Hibernate SessionFactory provides three methods through which we can get Session object.
1) getCurrentSession()
2) openSession()
3) openStatelessSession()

12) If you see a LazyInitializationException, it means that a Hibernate-managed object has lived longer than its session.
13) Managed objects are not portable between sessions. Trying to load an object in one session then save it into another session will also result in an error.
(You can use Session.load() or Session.get() to re-introduce an object to a new session,
but you’re much better off fixing whatever problem is causing you to try to move objects between sessions in the first place.
14) SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.
Different vendors have provided the implementation of Second Level Cache.
EH Cache
OS Cache
Swarm Cache
JBoss Cache

15) How to make an immutable class in hibernate?
If you mark a class as mutable=”false”, the class will be treated as an immutable class. By default, it is mutable=”true”.

16) What are the constraints on an entity class?
An entity class must fulfill the following requirements:

The class must have a no-argument constructor.
The class can’t be final.
The class must be annotated with @Entity annotation.
The class must implement a Serializable interface if value passes an empty instance as a detached object.

17) What is the purpose of cascading operations in JPA?
If we apply any task to one entity then using cascading operations, we make it applicable to its related entities also.

18) What are the types of cascade supported by JPA?
Following is the list of cascade type: -

PERSIST: In this cascade operation, if the parent entity is persisted then all its related entity will also be persisted.
MERGE: In this cascade operation, if the parent entity is merged, then all its related entity will also be merged.
DETACH: In this cascade operation, if the parent entity is detached, then all its related entity will also be detached.
REFRESH: In this cascade operation, if the parent entity is refreshed, then all its related entity will also be refreshed.
REMOVE: In this cascade operation, if the parent entity is removed, then all its related entity will also be removed.
ALL In this case, all the above cascade operations can be applied to the entities related to the parent entity.

19) The native UPDATE statement doesn’t use any entities and therefore doesn’t trigger any lifecycle event.

20) Spring Data uses the Repository pattern.

JpaRepository
MongoRepository
GemfireRepository

21) Using @GeneratedValue(strategy = GenerationType.IDENTITY) approach prevents Hibernate from using different optimization techniques like JDBC batching.

22) The no-argument constructor, which is also a JavaBean convention, is a requirement for all persistent classes. Hibernate needs to create objects for you, using Java Reflection. The constructor can be private. However, package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.

23) We recommend all new projects which make use of to use @GeneratedValue to also set hibernate.id.new_generator_mappings=true as the new generators are more efficient and closer to the JPA 2 specification semantic. However they are not backward compatible with existing databases (if a sequence or a table is used for id generation).

24) What are the exceptions thrown by the Spring DAO classes?
Spring DAO classes throw exceptions that are subclasses of org.springframework.dao.DataAccessException.
Spring translates technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception that are generic and easy to understand. These exceptions wrap the original exception.

25) Difference between CrudRepository and JpaRepository interfaces in Spring Data JPA.
JpaRepository extends PagingAndSortingRepository that extends CrudRepository.
CrudRepository mainly provides CRUD operations.
PagingAndSortingRepository provide methods to perform pagination and sorting of records.
JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.
Due to their inheritance nature, JpaRepository will have all the behaviors of CrudRepository and PagingAndSortingRepository.

26) How does @Transactional works in Spring?
@Transactional annotation is based on AOP concept.
When you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you are annotating. And when clients make calls into your object, the calls are intercepted and the behaviors gets injected via the proxy mechanism.
@Transactional annotation works similar to transactions in EJB.

27) When to use @RestController vs @RepositoryRestResource annotations in Spring.
@RestController annotation renders as Restful resource within a Controller while @RepositoryRestResource annotation exposes repository itself as a RESTful resource.

28) Does the transaction rollback on exception in spring declarative transaction management?
By default configuration only unchecked exceptions (that is, subclasses of java.lang.RuntimeException) are rollbacked and the transaction will still be commited in case of checked exceptions.
To enable rollbacking on checked exceptions add the parameter rollBackFor to the @Transactional attribute, for example, rollbackFor=Exception.class.
@Transactional(rollbackFor = Exception.class).

29) When to use JTA and JPA transaction manager?
If you want to delegate managed transactions to your application server and handle complex transactions across multiple resources you need to use the JtaTransactionManager.
But it is not needed in most cases, JpaTransactionManager, is the best choice.
JTA is global transaction while JPA is local.

30) Does Spring Transactional annotation support both global and local transactions?
Yes. The Spring Framework’s declarative transaction management works in any environment. It can work with JTA transactions or local transactions using JDBC, JPA, Hibernate or JDO.

31) Can Spring Transactional annotation be applied only for public methods?
Yes, only public methods. If you annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings.
Consider the use of AspectJ if you need to annotate non-public methods.

32) What are the default @Transactional settings?
Default propagation setting is PROPAGATION_REQUIRED.
Isolation level is ISOLATION_DEFAULT.
The transaction is read/write.
Transaction timeout defaults to the default timeout of the underlying transaction system, none if timeouts are not supported.
Any RuntimeException triggers rollback, and any checked Exception does not.

33) How do I decide between when to use prototype scope and singleton-scoped bean?
Use the prototype scope for all beans that are stateful and the singleton scope for stateless beans.

34) Difference between BeanFactory and ApplicationContext in spring.
With ApplicationContext more than one config files are possible while only one config file or .xml file is possible with BeanFactory.
ApplicationContext support internationalization messages, application life-cycle events, validation and many enterprise services like JNDI access, EJB integration etc. while BeanFactory doesn’t support any of these.

35) Which DI should I prefer, Constructor-based or setter-based in spring?
Use constructor-based DI for dependencies that are required (mandatory) and setters for dependencies that are optional.

36) What are Lazily-instantiated beans?
Spring instantiate all the beans at startup by default. But sometimes, some beans are not required to be initialized during startup, rather we want them to be initialized in later stages of the application on demand. For such beans, we include lazy-init=”true” while configuring beans.


<! — this bean will be lazily-instantiated… →

37) Difference between Dependency Injection and Factory Pattern.
Using factory your code is still actually responsible for creating objects. By DI you delegate that responsibility to another class or a framework, which is separate from your code.

Use of dependency injection results in loosely coupled design but the use of factory pattern create a tight coupling between factory and classes.

A disadvantage of Dependency injection is that you need a container and configuration to inject the dependency, which is not required in case of factory design pattern.

38) How does Spring achieve loose coupling?
Spring uses runtime polymorphism and encourages association (HAS-A relationship) rather than inheritance.

39) Is Spring DTD/XSD mandatory for XML validation? Where I can find the Spring DTD?
Yes, DTD or XSD is mandatory for Spring bean xml documents. spring-beans.jar file has the dtd (document type definition) file spring-beans.dtd under the package org.springframework.beans.factory.xml.

40) How do I Inject value into static variables in Spring bean?
Spring does not allow injecting to public static non-final fields, so the workaround will be changing to private modifier.

Another workaround will be to create a non static setter to assign the injected value for the static variable.

@Value(“${my.name}”)
public void setName(String privateName) {
ThisClass.name = privateName;
}

41) Is spring prototype bean threadsafe?
No. Prototype beans are stateful however if it is managed by multiple threads, then steps must be taken to ensure it is thread safe.

42) Is request scoped spring beans threadsafe?
Yes. Each request will get its own bean so thread safety is guaranteed.

43) What is the preferred bean scope for DAO, Service and Controller?
Singleton scope is preferred. DAO, service and controllers do not have to maintain its state.

44) Mention an alternate DI framework like Spring.
Google Guice framework.

45) What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?
Web Application context extends Application Context which is designed to work with the standard javax.servlet.ServletContext to communicate with the container.

Beans that are instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface.

46) What is the default scope of Spring MVC controllers?
Spring MVC controllers are singleton by default and any controller object variable/field will be shared across all the requests and sessions.

If the object variable should not be shared across requests, one can use @Scope(“request”) annotation above your controller class definition to create instance per request.

47) Sping MVC — pass model between controllers.
avoid redirect instead use forward.

48) Difference Between @RequestParam and @PathVariable in Spring MVC.
@RequestParam and @PathVariable annotations are used for accessing the values from the request.
The primary difference between @RequestParam and @PathVariable is that @RequestParam used for accessing the values of the query parameters where as @PathVariable used for accessing the values from the URI template.
Request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID “invoices”?

If the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:

@RequestMapping(value=”/user/{userId}/invoices”, method = RequestMethod.GET)
public List listUsersInvoices(
@PathVariable(“userId”) int user,
@RequestParam(value = “date”, required = false) Date dateOrNull) {

}

49) How do I configure DispatcherServlet without using web.xml in Spring MVC?
Create a class implementing WebApplicationInitializer interface and implement onStartup() method. In this method we can register all the annotation based application configuration classes, servlet and its mappings, listener etc including DispatcherServlet.

public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ApplicationConfig.class);
ctx.setServletContext(servletContext);
Dynamic dynamic = servletContext.addServlet(“dispatcher”, new DispatcherServlet(ctx));
dynamic.addMapping(“/”);
dynamic.setLoadOnStartup(1);
}
}

50) How do I create a Spring MVC controller without a view?
Set the controller method return type as void and mark the method with @ResponseBody annotation.

51) How do I return a string from the Spring MVC controller without a view?
Set the return type of the method as String and mark the method with @ResponseBody annotation.

@RequestMapping(value=”/returnHelloWorld”, method=GET)
@ResponseBody
public String returnHelloMethod() {
return “Hello world!”;
}

52) Explain @ResponseBody annotation in Spring MVC.
When a controller method is marked with @ResponseBody, spring deserializes the returned value of the method and writes it directly to the Http Response automatically.

The return value of the method constitute the body of the HTTP response and not placed in a Model, or interpreted as a view name.

53) Explain @RequestBody annotation in Spring MVC.
Spring automatically converts the content of the incoming request body to the parameter object when annotated with the @RequestBody annotation.

@ResponseBody @RequestMapping(“/getUserInfo”)
public String getUserInformation(@RequestBody UserDetails user){
return user.getFirstName() + “ “ + user.getLastName();
}

54) What does request.getParameter return when the parameter does not exist in Spring MVC/Servlet?
The return type of the getParamter is String and it returns null if the parameter does not exist.

55) How do you resolve SSLHandShakeException?
Installing Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files in your java 7/8 installation is one of the ways to resolve SSL handshake failure.

56) Is transaction managed at DAO or Service layer in Spring?
At service layer.

Credits:

Top comments (0)