Integration with Spring
Integration with Spring Interview with follow-up questions
1. Can you explain how Hibernate can be integrated with Spring?
Hibernate integrates with Spring through the Spring ORM module and, most commonly in modern applications, through Spring Data JPA which uses Hibernate as its default JPA provider.
Modern approach: Spring Boot 3 + Spring Data JPA + Hibernate 6
This is the current production standard. Add the dependency:
org.springframework.boot
spring-boot-starter-data-jpa
Spring Boot auto-configures:
- A
DataSource(via HikariCP by default) - A
LocalContainerEntityManagerFactoryBeanbacked by Hibernate - A
JpaTransactionManager - Spring Data repositories
All imports use jakarta.persistence (not javax.persistence).
import jakarta.persistence.*;
@Entity
public class Product {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
public interface ProductRepository extends JpaRepository {
List findByName(String name);
}
@Service
@Transactional
public class ProductService {
private final ProductRepository repo;
public ProductService(ProductRepository repo) { this.repo = repo; }
public Product create(Product p) { return repo.save(p); }
}
Key configuration (application.properties)
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=user
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Accessing native Hibernate Session when needed
@PersistenceContext
private EntityManager em;
public void doHibernateSpecific() {
Session session = em.unwrap(Session.class);
// use Hibernate-specific API here
}
Legacy approach (still seen in older codebases)
Older Spring 5 / Hibernate 5 codebases used LocalSessionFactoryBean, HibernateTransactionManager, and HibernateTemplate. These are still functional but represent a legacy pattern — most new code uses Spring Data JPA.
Key interview gotchas
- Spring Boot 3 requires Hibernate 6 and
jakarta.persistence; usingjavax.persistenceimports causes compile errors. @Transactionalfromorg.springframework.transaction.annotation— not fromjakarta— is what Spring manages.- Do not mix Spring-managed transactions with raw Hibernate transaction calls (
session.beginTransaction()) — this breaks Spring's transaction synchronization.
Follow-up 1
What are the benefits of integrating Hibernate with Spring?
Integrating Hibernate with Spring offers several benefits:
- Simplified configuration: Spring provides a simplified way to configure Hibernate, reducing the amount of boilerplate code required.
- Transaction management: Spring's transaction management capabilities can be used to manage transactions in Hibernate, ensuring data consistency and integrity.
- Dependency injection: Spring's dependency injection can be used to inject Hibernate SessionFactory and other Hibernate components into your application, making it easier to manage and test.
- AOP support: Spring's AOP (Aspect-Oriented Programming) support can be used to add additional functionality to Hibernate, such as logging, caching, and security.
- Integration with other Spring features: Integrating Hibernate with Spring allows you to leverage other Spring features, such as Spring MVC for web applications and Spring Security for authentication and authorization.
Follow-up 2
Can you describe a scenario where you have integrated Hibernate with Spring?
Sure! One common scenario is building a web application where Hibernate is used as the ORM framework and Spring is used for dependency injection and transaction management. In this scenario, you can configure the Hibernate SessionFactory and transaction management in the Spring configuration file. Then, you can use Spring's dependency injection to inject the SessionFactory into your DAO (Data Access Object) classes. This allows you to easily perform database operations using Hibernate within your Spring application. Additionally, you can use Spring's transaction management to manage transactions in Hibernate, ensuring data consistency and integrity.
Follow-up 3
What are the steps to integrate Hibernate with Spring?
To integrate Hibernate with Spring, you can follow these steps:
- Add the necessary dependencies: Include the required Hibernate and Spring ORM dependencies in your project.
- Configure the Hibernate SessionFactory: Define the Hibernate SessionFactory bean in the Spring configuration file. Configure the database connection details, mapping files, and other Hibernate properties.
- Configure transaction management: Configure the transaction manager bean in the Spring configuration file. You can use Spring's built-in transaction managers or define a custom transaction manager.
- Inject the SessionFactory: Use Spring's dependency injection to inject the SessionFactory into your DAO classes or other components that need to access the database.
- Use Hibernate within your Spring application: Use the injected SessionFactory to perform database operations using Hibernate within your Spring application.
Follow-up 4
What is the role of SessionFactory in integrating Hibernate with Spring?
The SessionFactory is a key component in integrating Hibernate with Spring. It is responsible for creating and managing Hibernate Session objects, which represent a connection to the database. In the context of Spring and Hibernate integration, the SessionFactory is typically configured as a bean in the Spring configuration file. Spring manages the lifecycle of the SessionFactory and ensures that only one instance is created and shared across the application. By injecting the SessionFactory into your DAO classes or other components, you can easily perform database operations using Hibernate within your Spring application.
Follow-up 5
Can you explain how transaction management is handled in Spring-Hibernate integration?
In Spring-Hibernate integration, transaction management is handled by Spring's transaction management capabilities. Spring provides various ways to manage transactions, including declarative transaction management and programmatic transaction management.
Declarative transaction management is the most common approach in Spring-Hibernate integration. It involves configuring transactional behavior declaratively using annotations or XML-based configuration. You can annotate your service methods or DAO methods with the @Transactional annotation to define transaction boundaries. Spring intercepts the method calls and automatically starts, commits, or rolls back transactions based on the configured transactional behavior.
Programmatic transaction management is an alternative approach where you explicitly manage transactions using Spring's TransactionTemplate or PlatformTransactionManager API. With programmatic transaction management, you have more fine-grained control over transaction boundaries and can handle exceptions and rollbacks manually.
Both approaches provide a convenient way to manage transactions in Spring-Hibernate integration, ensuring data consistency and integrity.
2. What is the role of Spring's HibernateTemplate?
HibernateTemplate is a Spring ORM helper class that was designed to simplify Hibernate data access code by wrapping the SessionFactory and handling session/transaction boilerplate. It is a legacy API and has been effectively deprecated since Spring 4.
What it did
- Managed session lifecycle (open, close, exception translation).
- Translated Hibernate-specific exceptions into Spring's
DataAccessExceptionhierarchy. - Provided convenience methods like
get(),save(),delete(),find(),execute().
// Legacy Spring + Hibernate 4 pattern
@Repository
public class UserDao {
@Autowired
private HibernateTemplate hibernateTemplate;
public User findById(Long id) {
return hibernateTemplate.get(User.class, id);
}
public void save(User user) {
hibernateTemplate.save(user);
}
}
Why it is no longer recommended
- Hibernate's
SessionFactorywith Spring's@Transactionalprovides the same session/exception management without any template. HibernateTemplatetightly couples DAOs to the Spring ORM module.- Spring Data JPA makes explicit DAO classes largely unnecessary.
Modern replacement
Inject EntityManager directly and use Spring Data JPA repositories:
// Modern approach (Spring Boot 3 / Hibernate 6)
@Repository
public class UserDao {
@PersistenceContext
private EntityManager em;
public User findById(Long id) {
return em.find(User.class, id);
}
}
// Or even simpler — no DAO class needed:
public interface UserRepository extends JpaRepository { }
Key interview gotchas
HibernateTemplateis still present in Spring Framework but is not recommended for any new development.- The exception translation it provided (
HibernateException→DataAccessException) is now handled automatically when@Repositoryis combined with aPersistenceExceptionTranslationPostProcessorbean — present by default in Spring Boot. - If asked about
HibernateTemplate, acknowledge its purpose but pivot to the modern approach — interviewers are testing whether you know it is legacy.
Follow-up 1
Can you explain how HibernateTemplate simplifies data access code?
HibernateTemplate simplifies data access code by encapsulating common database operations, such as saving, updating, deleting, and querying objects, into template methods. These template methods handle the creation and management of Hibernate Sessions, transaction management, exception handling, and resource cleanup, allowing developers to focus on the business logic instead of dealing with low-level database operations.
Follow-up 2
What are the advantages and disadvantages of using HibernateTemplate?
Advantages of using HibernateTemplate:
- Simplifies data access code by providing a higher-level abstraction
- Handles the creation and management of Hibernate Sessions, transaction management, exception handling, and resource cleanup
- Reduces boilerplate code
Disadvantages of using HibernateTemplate:
- HibernateTemplate is considered a legacy class in Spring and is not recommended for new projects. It has been deprecated since Spring 3.1 and is no longer actively maintained.
- It may not support all the latest features and improvements introduced in newer versions of Hibernate.
- It adds an additional layer of abstraction, which can make the code harder to understand and maintain in some cases.
Follow-up 3
Can you provide an example of using HibernateTemplate?
Sure! Here's an example of using HibernateTemplate to save an object to the database:
public class UserDao {
private HibernateTemplate hibernateTemplate;
public void saveUser(User user) {
hibernateTemplate.save(user);
}
}
Follow-up 4
How does HibernateTemplate handle exception translation?
HibernateTemplate handles exception translation by automatically converting Hibernate-specific exceptions into Spring's DataAccessException hierarchy. This allows the application to catch and handle exceptions in a consistent and uniform way, regardless of the underlying persistence technology being used. HibernateTemplate uses Spring's HibernateExceptionTranslator to perform the exception translation.
Follow-up 5
What is the difference between using HibernateTemplate and using plain Hibernate?
The main difference between using HibernateTemplate and using plain Hibernate is the level of abstraction and the amount of boilerplate code required. HibernateTemplate provides a higher-level abstraction and simplifies data access code by encapsulating common database operations into template methods. It handles the creation and management of Hibernate Sessions, transaction management, exception handling, and resource cleanup. On the other hand, using plain Hibernate requires more manual configuration and coding, as developers need to explicitly manage Hibernate Sessions, transactions, and exception handling. However, it also provides more flexibility and control over the database operations, allowing for fine-grained customization if needed.
3. How does Spring manage transactions when integrated with Hibernate?
Spring manages Hibernate transactions through its platform transaction management abstraction. The key mechanism is JpaTransactionManager (in Spring Boot setups) combined with Spring's @Transactional annotation.
How it works
Spring's @Transactional uses AOP to intercept annotated methods. When a transactional method is entered, Spring's TransactionInterceptor asks the configured PlatformTransactionManager to open a transaction. For JPA/Hibernate, this binds an EntityManager (and its underlying JDBC connection) to the current thread. When the method exits, Spring commits or rolls back based on the outcome.
@Service
public class OrderService {
private final OrderRepository orderRepository;
public OrderService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Transactional
public Order placeOrder(Order order) {
// EntityManager is bound to this thread's transaction
return orderRepository.save(order);
}
@Transactional(readOnly = true)
public Order getOrder(Long id) {
return orderRepository.findById(id).orElseThrow();
}
}
JpaTransactionManager vs HibernateTransactionManager
| Manager | When to use |
|---|---|
JpaTransactionManager |
Spring Boot 3 + Spring Data JPA (standard) |
HibernateTransactionManager |
Direct SessionFactory usage without JPA layer |
Spring Boot auto-configures JpaTransactionManager when spring-boot-starter-data-jpa is on the classpath.
@Transactional key attributes
readOnly = true: hints Hibernate to skip dirty checking and flush — improves performance for read-only queries.propagation:REQUIRED(default, joins existing),REQUIRES_NEW(starts a new transaction),SUPPORTS,MANDATORY, etc.rollbackFor: specifies which exceptions trigger rollback (by default, unchecked exceptions roll back; checked exceptions do not).isolation: maps to JDBC isolation levels (READ_COMMITTED,SERIALIZABLE, etc.).
Key interview gotchas
@Transactionalonly works on Spring-managed beans — it has no effect onnew MyService()directly.- Self-invocation (calling a
@Transactionalmethod from within the same bean) bypasses the AOP proxy and the transaction — use@Autowiredself-injection orApplicationContextto get the proxy, or restructure the code. readOnly = truedoes not prevent write operations at the JPA level but disables Hibernate's dirty-checking flush on commit, which is a meaningful performance optimization.- Mixing Spring's
@Transactionalwith Hibernate's nativesession.beginTransaction()breaks transaction synchronization and must be avoided.
Follow-up 1
What is the role of @Transactional annotation in Spring-Hibernate integration?
The @Transactional annotation is used to mark a method or class as transactional in Spring-Hibernate integration. It allows you to specify the transactional behavior for the annotated method or class. This annotation can be used with various attributes to control the transactional behavior, such as propagation, isolation level, rollback rules, and more.
Follow-up 2
Can you explain how propagation behavior works in Spring transaction management?
Propagation behavior in Spring transaction management defines how transactions should be propagated from one method to another. Spring provides different propagation behaviors, such as REQUIRED, REQUIRES_NEW, SUPPORTS, MANDATORY, NOT_SUPPORTED, and NEVER. These propagation behaviors determine whether a new transaction should be created or an existing transaction should be used when a method is called within the scope of a transaction.
Follow-up 3
What is the difference between programmatic and declarative transaction management in Spring?
Programmatic transaction management in Spring involves manually managing transactions using the TransactionTemplate or the PlatformTransactionManager interface. It requires explicit transaction begin, commit, and rollback statements in the code. On the other hand, declarative transaction management in Spring allows you to define transactional behavior using annotations or XML configuration. The transaction management is handled by Spring AOP, and you don't need to write explicit transaction management code.
Follow-up 4
How does Spring handle rollback in case of an exception?
In Spring, if an exception occurs within a transactional method, Spring automatically rolls back the transaction by default. This means that any changes made within the transaction will be undone, and the database will be restored to its previous state. You can also customize the rollback behavior using the @Transactional annotation's rollbackFor and noRollbackFor attributes to specify which exceptions should trigger a rollback or not.
Follow-up 5
Can you provide an example of a transaction management scenario in Spring-Hibernate integration?
Sure! Here's an example of a transaction management scenario in Spring-Hibernate integration:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void updateUser(User user) {
try {
userRepository.update(user);
// Perform other business logic
} catch (Exception e) {
// Handle exception
}
}
}
In this example, the updateUser method is marked as @Transactional, which means that it will be executed within a transaction. If any exception occurs during the execution, the transaction will be rolled back, ensuring data consistency.
4. What is the role of LocalSessionFactoryBean in Spring-Hibernate integration?
LocalSessionFactoryBean is a Spring FactoryBean that creates and configures a Hibernate SessionFactory and exposes it as a Spring bean. It is the classic bridge between Spring's IoC container and Hibernate's native API.
Role and responsibilities
- Accepts Hibernate configuration (properties, entity packages, mapping files).
- Integrates with Spring's
DataSourcebean for connection management. - Exposes a fully configured
SessionFactorythat Spring can inject into DAOs and services. - Enables use of
HibernateTransactionManagerfor Spring-managed transactions over Hibernate native sessions.
Typical configuration (Java config)
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
@Autowired
private DataSource dataSource;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
sf.setDataSource(dataSource);
sf.setPackagesToScan("com.example.domain");
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.put("hibernate.show_sql", "true");
props.put("hibernate.hbm2ddl.auto", "validate");
sf.setHibernateProperties(props);
return sf;
}
@Bean
public HibernateTransactionManager transactionManager(SessionFactory sf) {
return new HibernateTransactionManager(sf);
}
}
LocalSessionFactoryBean vs LocalContainerEntityManagerFactoryBean
| Bean | API | Use when |
|---|---|---|
LocalSessionFactoryBean |
Hibernate native (SessionFactory) |
Direct Hibernate API, not JPA |
LocalContainerEntityManagerFactoryBean |
JPA (EntityManagerFactory) |
Spring Data JPA, standard JPA code |
Spring Boot context
In Spring Boot 3 with spring-boot-starter-data-jpa, you do not configure either of these beans manually — HibernateJpaAutoConfiguration sets up LocalContainerEntityManagerFactoryBean automatically. LocalSessionFactoryBean is mainly encountered in legacy Spring XML/Java config that predates Spring Boot, or in applications that need Hibernate-native features not exposed through JPA.
Key interview gotchas
LocalSessionFactoryBeancreates aSessionFactory;LocalContainerEntityManagerFactoryBeancreates anEntityManagerFactory. In Hibernate,SessionFactoryimplementsEntityManagerFactory, so you canunwrap()between them.- Spring Boot does not configure
LocalSessionFactoryBeanautomatically — if you add it, you own the full Hibernate configuration. - In Hibernate 6 + Spring Boot 3,
javax.persistenceis gone; any legacy config using it will fail.
Follow-up 1
How does LocalSessionFactoryBean help in creating a SessionFactory?
LocalSessionFactoryBean helps in creating a SessionFactory by providing a convenient way to configure and initialize the SessionFactory. It allows you to specify various properties and settings required for Hibernate, such as the database connection details, mapping files, and Hibernate-specific configuration options. The LocalSessionFactoryBean then uses these settings to create and configure the SessionFactory.
Follow-up 2
Can you provide an example of configuring LocalSessionFactoryBean?
Sure! Here's an example of configuring LocalSessionFactoryBean in a Spring XML configuration file:
org.hibernate.dialect.MySQL5Dialect
true
com/example/Entity1.hbm.xml
com/example/Entity2.hbm.xml
Follow-up 3
What is the difference between using LocalSessionFactoryBean and AnnotationSessionFactoryBean?
The main difference between LocalSessionFactoryBean and AnnotationSessionFactoryBean is the way they handle the configuration of Hibernate. LocalSessionFactoryBean is typically used for XML-based configuration, where you define the Hibernate properties and mapping files explicitly in the Spring XML configuration file. On the other hand, AnnotationSessionFactoryBean is used for annotation-based configuration, where you use Hibernate annotations to define the mapping metadata and rely on Spring's auto-configuration to set up the SessionFactory.
Follow-up 4
How does LocalSessionFactoryBean handle DataSource configuration?
LocalSessionFactoryBean handles DataSource configuration by allowing you to set the DataSource bean reference using the 'dataSource' property. You can either define the DataSource bean separately in the Spring XML configuration file and reference it, or you can let Spring auto-configure the DataSource based on the application's database configuration. The LocalSessionFactoryBean will then use the specified DataSource to establish a connection to the database and perform database operations.
Follow-up 5
Can you explain how LocalSessionFactoryBean supports transaction management?
LocalSessionFactoryBean supports transaction management by integrating with Spring's transaction management capabilities. You can configure transaction management for the SessionFactory by using Spring's transaction management annotations or XML-based configuration. By default, LocalSessionFactoryBean uses Spring's HibernateTransactionManager to manage transactions. This allows you to easily control the transaction boundaries and apply declarative transaction management to your Hibernate operations.
5. Can you explain how Spring's JdbcTemplate can be used with Hibernate?
Using Spring's JdbcTemplate alongside Hibernate in the same application is a valid pattern — they can share the same DataSource and participate in the same Spring-managed transactions. This comes up when you need raw SQL for complex reporting queries or bulk operations that are awkward in HQL.
Sharing the DataSource
Both JdbcTemplate and Hibernate's EntityManagerFactory / SessionFactory are configured with the same DataSource bean. Spring's transaction manager ensures they participate in the same JDBC connection/transaction:
@Configuration
public class DataConfig {
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
// DataSource is also wired into Hibernate via Spring Boot auto-config
}
Mixing JdbcTemplate and Hibernate in a service
@Service
@Transactional
public class ReportService {
private final JdbcTemplate jdbc;
private final OrderRepository orderRepo; // Spring Data JPA
public ReportService(JdbcTemplate jdbc, OrderRepository orderRepo) {
this.jdbc = jdbc;
this.orderRepo = orderRepo;
}
public void processAndReport(Long orderId) {
// Hibernate for domain operations
Order order = orderRepo.findById(orderId).orElseThrow();
order.setStatus("PROCESSED");
// JdbcTemplate for complex reporting query
List> stats = jdbc.queryForList(
"SELECT date_trunc('month', created_at) AS month, COUNT(*) AS cnt " +
"FROM orders GROUP BY 1 ORDER BY 1"
);
// Both operations run in the same transaction
}
}
Important: flush before JdbcTemplate reads
Hibernate buffers writes until flush. If you write via Hibernate and then read via JdbcTemplate in the same transaction, you may not see the Hibernate-written data unless you flush first:
em.flush(); // push pending Hibernate changes to the DB connection
// Now JdbcTemplate can see those changes
jdbc.queryForList("SELECT ...");
When to use JdbcTemplate alongside Hibernate
- Complex aggregate/reporting queries that would be awkward in JPQL.
- Bulk UPDATE/DELETE where Hibernate's change tracking adds unnecessary overhead.
- Calling stored procedures or using database-specific features not covered by JPQL.
Key interview gotchas
- Both must use the same
DataSourceto participate in the same transaction — using separate data sources means separate transactions. JdbcTemplatebypasses Hibernate's first-level cache — reads viaJdbcTemplatedo not populate the Hibernate session cache.- Spring Boot auto-configures
JdbcTemplateautomatically whenspring-boot-starter-jdbcorspring-boot-starter-data-jpais on the classpath.
Follow-up 1
What are the benefits of using JdbcTemplate in Spring-Hibernate integration?
There are several benefits of using JdbcTemplate in Spring-Hibernate integration:
Simplified database operations: JdbcTemplate provides a higher-level abstraction over plain JDBC, making it easier to perform database operations.
Automatic resource management: JdbcTemplate takes care of resource management, such as opening and closing database connections, and releasing database resources after use.
Exception handling: JdbcTemplate handles SQLExceptions and translates them into Spring's DataAccessException hierarchy, making it easier to handle database exceptions.
Integration with Spring's transaction management: JdbcTemplate integrates seamlessly with Spring's transaction management, allowing you to perform database operations within a transactional context.
Improved code readability and maintainability: JdbcTemplate provides a clean and concise API for executing SQL queries and updates, making the code more readable and maintainable.
Follow-up 2
Can you provide an example of using JdbcTemplate with Hibernate?
Sure! Here's an example of using JdbcTemplate with Hibernate:
@Repository
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
private SessionFactory sessionFactory;
@Autowired
public EmployeeDao(JdbcTemplate jdbcTemplate, SessionFactory sessionFactory) {
this.jdbcTemplate = jdbcTemplate;
this.sessionFactory = sessionFactory;
}
public List getAllEmployees() {
return jdbcTemplate.query("SELECT * FROM employees", new EmployeeRowMapper());
}
public void saveEmployee(Employee employee) {
Session session = sessionFactory.getCurrentSession();
session.save(employee);
}
// Other methods...
}
In this example, the EmployeeDao class uses JdbcTemplate to execute a SELECT query and retrieve a list of employees. It also uses Hibernate's SessionFactory to save an employee object to the database.
Follow-up 3
How does JdbcTemplate handle exception translation?
JdbcTemplate handles exception translation by automatically converting SQLExceptions into Spring's DataAccessException hierarchy. This allows you to handle database exceptions in a consistent and uniform way, regardless of the underlying database technology.
When an SQLException occurs during the execution of a JdbcTemplate method, JdbcTemplate catches the exception and translates it into an appropriate subclass of DataAccessException. This hierarchy includes exceptions such as DataAccessException, DuplicateKeyException, IncorrectResultSizeDataAccessException, and many more.
By using exception translation, you can write exception handling code that is independent of the specific database technology being used. This makes it easier to switch between different databases or ORM frameworks without having to change your exception handling code.
Follow-up 4
What is the difference between using JdbcTemplate and using plain JDBC?
The main difference between using JdbcTemplate and using plain JDBC is the level of abstraction and the amount of boilerplate code required.
When using plain JDBC, you need to manually manage database resources such as opening and closing connections, creating and executing statements, handling exceptions, and releasing resources after use. This can result in a lot of boilerplate code and makes the code more error-prone.
On the other hand, JdbcTemplate provides a higher-level abstraction over plain JDBC. It takes care of resource management, exception handling, and provides a convenient way to execute SQL queries and updates. JdbcTemplate eliminates the need for manual resource management and reduces the amount of boilerplate code required.
Using JdbcTemplate can make your code more concise, readable, and maintainable. It also provides integration with Spring's transaction management, allowing you to perform database operations within a transactional context.
Follow-up 5
Can you explain how JdbcTemplate supports named parameters?
Yes, JdbcTemplate supports named parameters for executing SQL queries and updates. Named parameters allow you to specify parameters in the SQL query using names instead of the traditional '?' placeholders.
To use named parameters with JdbcTemplate, you can use the NamedParameterJdbcTemplate class. This class extends JdbcTemplate and provides additional methods for executing SQL queries and updates with named parameters.
Here's an example of using named parameters with JdbcTemplate:
@Repository
public class EmployeeDao {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
public EmployeeDao(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
public List getEmployeesByDepartment(String department) {
String sql = "SELECT * FROM employees WHERE department = :department";
Map params = new HashMap<>();
params.put("department", department);
return namedParameterJdbcTemplate.query(sql, params, new EmployeeRowMapper());
}
// Other methods...
}
In this example, the EmployeeDao class uses NamedParameterJdbcTemplate to execute a SELECT query with a named parameter (:department). The parameter value is specified in a Map, and the query method automatically substitutes the named parameter with the corresponding value.
6. How does Spring Boot 3 auto-configure Hibernate, and what are the key application.properties settings?
Spring Boot 3 auto-configures Hibernate via spring-boot-starter-data-jpa, which sets up:
- A
DataSource(HikariCP connection pool by default) - A
LocalContainerEntityManagerFactoryBean(wraps Hibernate'sSessionFactory) - A
JpaTransactionManager - Spring Data JPA repositories
Key application.properties settings:
# DDL generation: none | validate | update | create | create-drop
spring.jpa.hibernate.ddl-auto=validate
# Show generated SQL in logs
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
# Bind SQL parameter values in logs (Hibernate 6)
logging.level.org.hibernate.orm.jdbc.bind=TRACE
# Second-level cache (example with Ehcache/JCache)
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory
# Batch inserts/updates
spring.jpa.properties.hibernate.jdbc.batch_size=25
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
# Open-in-view: DISABLE in production (causes performance/connection issues)
spring.jpa.open-in-view=false
spring.jpa.open-in-view=false is the most important property many developers overlook. By default it is true in Spring Boot, which keeps a Hibernate session open for the entire HTTP request (allowing lazy loading in views) — but this holds a database connection for the duration of the request and leads to connection pool exhaustion under load. Always disable it in production.
Live mock interview
Mock interview: Integration with Spring
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.