Spring Data JPA integration to Spring MVC (Java Configuration)

Syed Hasan
2 min readFeb 9, 2020

In this part we will integrate Spring Data Jpa in Spring MVC and modify our previous Hibernate based service classes and re-write them with Spring Data JPA. To get existing source code, click here.

  1. Adding dependency

Firstly, we need to add the dependency of Spring Data JPA in our existing project.

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>

Note that, the dependency version will be current version from maven repository.

2. Configuration

Now, in our existing HibernateConfig class, we will annotate the class with @EnableJpaRepositories(“com.spring5.practice.repositories”) [ Replace the repository package name with your package name]. We will modify our getSession() method and add 2 more beans. One is entityManagerFactory bean, another one is transactionManager bean. After adding these, the class will look like the code below.

@EnableJpaRepositories("com.spring5.practice.repositories")
@PropertySource ("classpath:hibernate.properties")
@Configuration
public class HibernateConfig {

@Value ("${hibernate.hbm2ddl.auto}")
private String HBM2DDL_AUTO;
@Value ("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
@Value ("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
@Value ("${hibernate.connection.password}")
private String DB_PASSWORD;
@Value ("${hibernate.connection.username}")
private String DB_USER;
@Value ("${hibernate.connection.url}")
private String DB_URL;
@Value ("${hibernate.connection.driver_class}")
private String DB_DRIVER_CLASS;

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER_CLASS);
dataSource.setUrl(DB_URL); //MySQL Specific: +"?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false"
dataSource.setUsername(DB_USER);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}

@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("com.spring5.practice.model");
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
hibernateProperties.put("hibernate.connection.autocommit", false);
hibernateProperties.put("hibernate.enable_lazy_load_no_trans", true);
sessionFactoryBean.setHibernateProperties(hibernateProperties);

return sessionFactoryBean;
}

@Bean
public EntityManagerFactory entityManagerFactory() {

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.spring5.practice.model");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();

return factory.getObject();
}

@Bean("transactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}

Also we have to scan the config package in RootConfig class.

3. Writing Repositories

Now we will create a new package called repositories and create our repositories. I have demonstrated the CourseRepository interface below.

@Repository
@Transactional
public interface CourseRepository extends JpaRepository<Course, Long>{

Course findByCourseId(Long id);

Course findByCourseCode(String courseCode);
}

To understand better about repositories, check out the Spring Data JPA reference documentation.

4. Calling repository methods from our Service classes

We will replace the old school Hibernate codes from our service classes and call the repository methods for our database interactions. The following code demonstrates the CourseService modifications.

@Service
@Transactional
public class CourseService {

@Autowired
private CourseRepository courseRepository;

public void addCourse(Course course) {
checkCourseInDb(course);
course.setCourseCode(course.getCourseName().substring(0, 2));
courseRepository.save(course);
}

private void checkCourseInDb(Course c) {
var course = courseRepository.findByCourseCode(c.getCourseCode());
if (course != null) {
throw new ResourceAlreadyExistsException("Course Already exists");
}
}

public void saveEditedCourse(Course c) {

var course = courseRepository.findByCourseId(c.getCourseId());
BeanUtils.copyProperties(c, course);
courseRepository.save(course);

}

public Course getCourseByCourseCode(String courseCode) {
var course = courseRepository.findByCourseCode(courseCode);
return course;
}

public List<Course> getAllCourses() {
return courseRepository.findAll();
}
}

Once we have done all these properly, our project will run successfully.

To get the updated source code, click here.

--

--

Syed Hasan
Syed Hasan

Written by Syed Hasan

Software Engineer | Back-End Developer | Spring Developer | Cloud Enthusiast

Responses (1)