Java.Hibernate.Medium.How do you configure Hibernate with Spring (e.g., LocalSessionFactoryBean)?

Short Answer

In a traditional Spring (non-Spring Boot) app, you configure Hibernate using LocalSessionFactoryBean to create the Hibernate SessionFactory, set up a DataSource, and configure a HibernateTransactionManager for declarative transactions.

🔎 Detailed Explanation

Here’s a typical setup in a Spring Java config class:


🔹 1) DataSource Bean
You first configure a DataSource that Hibernate will use for database connections:

@Bean
public DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setUrl("jdbc:postgresql://localhost:5432/mydb");
    ds.setUsername("username");
    ds.setPassword("password");
    return ds;
}

🔹 2) LocalSessionFactoryBean
This Spring bean wires Hibernate’s SessionFactory:

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
    factory.setDataSource(dataSource());
    factory.setPackagesToScan("com.myapp.model"); // entities
    factory.setHibernateProperties(hibernateProperties());
    return factory;
}

🔹 3) Hibernate properties
You set properties like dialect, show_sql, etc.:

private Properties hibernateProperties() {
    Properties props = new Properties();
    props.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    props.put("hibernate.show_sql", "true");
    props.put("hibernate.hbm2ddl.auto", "update");
    return props;
}

🔹 4) Transaction Manager
To integrate Hibernate’s transactions with Spring’s @Transactional:

@Bean
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
    return new HibernateTransactionManager(sessionFactory);
}

✅ This allows you to use @Transactional in your services.

🔹 5) Enable transaction management
In your config class:

@Configuration
@EnableTransactionManagement
public class HibernateConfig {
    // Beans defined here (DataSource, SessionFactory, TransactionManager)
}

📊 What does LocalSessionFactoryBean do?

✅ Scans your entity packages.
✅ Builds the Hibernate SessionFactory.
✅ Integrates with Spring’s dependency injection and lifecycle management.

🔹 Spring Boot note
In Spring Boot, you usually don’t need this → Boot auto-configures Hibernate via spring.jpa.* properties, but LocalSessionFactoryBean is still useful when you want fine-grained control in non-Boot Spring apps.


📌 Key Takeaways

LocalSessionFactoryBean is the classic way to configure Hibernate in Spring XML or Java config.
✅ Wire it with a DataSource and HibernateTransactionManager for full Hibernate/Spring integration.
✅ Don’t forget @EnableTransactionManagement to make @Transactional work.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.