Spring Boot Hibernate

Hibernate has been used with spring for as long as I can remember. Now that spring boot and spring data have taken the game by storm spring boot with hibernate are no longer relevant. But just in case you are not too familiar with Spring data or you want to keep using hibernate the old school way. Here is how you can use hibernate with spring boot.

Step 1 – Create a spring boot project using spring initializr and make sure you include these dependencies.

<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
</dependency>
<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
</dependency>

Step 2 – Configure hibernate using java

@Configuration
@EnableTransactionManagement
public class HibernateConfig {
	
	@Bean
	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());

		sessionFactory.setHibernateProperties(hibernateProperties());
		sessionFactory.setAnnotatedClasses(User.class, Role.class, Address.class);

		return sessionFactory;
	}
	
	private final Properties hibernateProperties() {
		final Properties hibernateProperties = new Properties();
		hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
		hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
		hibernateProperties.setProperty("hibernate.show_sql", "true");
		hibernateProperties.setProperty("hibernate.format_sql", "true");
		return hibernateProperties;
	}
	
	@Bean
	public DataSource dataSource() {
		Integer port = 3306;
		String host = "localhost";
		String username = "root";
		String password = "";
		String dbName = "spring_boot_hibernate";
		String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName
				+ "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
		return DataSourceBuilder.create().password(password).username(username).url(url).type(HikariDataSource.class)
				.build();
	}

	@Bean
	public PlatformTransactionManager hibernateTransactionManager() {
		HibernateTransactionManager transactionManager = new HibernateTransactionManager();
		transactionManager.setSessionFactory(sessionFactory().getObject());
		return transactionManager;
	}

	
}

If you using a hibernate xml file, you can simply just import to your java hibernate class.

@Configuration
@EnableTransactionManagement
@ImportResource({"classpath:hibernateConfiguration.xml"})
public class HibernateConfig {
    //
}

Step 3 – Create a DAO class for accessing the database.

@Repository
public class UserDAO {
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    private SessionFactory sessionFactory;

	
	public User saveAndFlush(User user) {
		log.debug("saveAndFlush(..)");
		Session session = sessionFactory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		Object id = session.save(user);
		transaction.commit();
		session.close();
		log.debug("id={}",ObjectUtils.toJson(id));
		user.setId((long)id);
		
		return user;
	}
	
	public User update(User user) {
		log.debug("update(..)");
		Session session = sessionFactory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.update(user);
		transaction.commit();
		session.close();
		
		return this.getById(user.getId());
	}
	
	public User getById(Long memberId) {
		Session session = sessionFactory.openSession();
		return session.get(User.class, memberId);
	}
}

Just like that and you back in business with spring boot and hibernate. Springboot makes you life as a developer so much easier.

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *