☰ See All Chapters |
Spring Data JPA Example
In this tutorial we will learn to create spring data JPA example application using maven. You have to follow our steps to create the example. Our steps are so easy and simple that you no need to have any prior knowledge on JPA (Java Persistence API).
Create java Project using Maven
In the command prompt execute the following maven command to generate Maven supported Java project named as “SpringDataJPAExample”.
mvn archetype:generate -DgroupId=com.java4coding -DartifactId=SpringDataJPAExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command creates a new maven Java project with the name “SpringDataJPAExample”, with complete directory structure.
Convert to eclipse project
To import Maven project into Eclipse IDE, in terminal, navigate inside “SpringDataJPAExample” project (folder should has pom.xml file), and issue mvn eclipse:eclipse command.
Import converted project into Eclipse IDE
In Eclipse IDE, Choose File –> Import –> General -> Existing Projects into Workspace –>Choose your project folder location. Done
Add the resources folder
We have to create a folder to place resources of a project and this folder has to be added to the classpath. To add the folder and to add the folder to the classpath, follow the below steps.
Right click on the project and select -> Build Path -> Configure Build Path, click on the Source tab and then click on Add Folder button as shown below.
Type resources, and click Finish.
Click on OK and then Apply and Close.
Add dependencies in pom.xml
Add the below Spring Data JAP, hibernate, mysql and other dependencies in pom.xml file. We are using mysql 8.0 and java 8 for this project.
pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java4coding</groupId> <artifactId>SpringDataJPAExample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>SpringDataJPAExample</name> <url>https://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.1.4.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.14</version> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> |
Issue the “mvn eclipse:eclipse“, in command prompt, Maven will download all Spring Data JAP, Hibernate, JPA and MySQL jars automatically and put into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse “.classpath” for dependency purpose.
It is tedious to open command prompt going out of eclipse again and again. Hence install terminal plugin into eclipse.
To open command prompt/terminal quickly from eclipse install below plugin.
After this plugin installation, just press Ctrl+Alt+T to open a local command prompt (Terminal).
Database script
CREATE TABLE STUDENT ( ID INT NOT NULL AUTO_INCREMENT, FIRSTNAME VARCHAR(20) DEFAULT NULL, LASTNAME VARCHAR(20) DEFAULT NULL, PRIMARY KEY (ID) );
|
Creating persistence.xml file
Create META-INF folder inside resources directory. Create persistence.xml inside META-INF folder.
Add following code in persistence.xml file.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="https://java.sun.com/xml/ns/persistence" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://java.sun.com/xml/ns/persistence https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="StudentPU"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" /> <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.archive.autodetection" value="class" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence> |
Create Entity class
Create the package com.java4coding and class Student.
Student.java
package com.java4coding;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;
@Entity public class Student {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName;
public Student() { super(); }
public Student(String firstName, String lastName) { super(); this.firstName = firstName; this.lastName = lastName; }
//Setters and getters public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
@Override public String toString() { return "Student [firstName=" + firstName + ", lastName=" + lastName + "]"; } } |
Create Repository
StudentRepository.java
package com.java4coding;
import org.springframework.data.repository.CrudRepository;
public interface StudentRepository extends CrudRepository<Student, Long>{ } |
Create Service Class
StudentService.java
package com.java4coding;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
@Service("studentService") public class StudentService { @Autowired private StudentRepository repository;
public void test() { // Save a new student Student student = new Student("Manu", "Manjunatha");
repository.save(student);
// Find a customer by ID Optional<Student> result = repository.findById(1L); result.ifPresent(student1 -> System.out.println(student));
// List all students Iterable<Student> iterator = repository.findAll(); iterator.forEach(student3 -> System.out.println(student3));
// Count number of customer long count = repository.count(); System.out.println("Number of students: " + count); } } |
Create Spring Configuration class
AppConfig.java
package com.java4coding;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
@Configuration @EnableJpaRepositories(basePackages = {"com.java4coding"}) public class AppConfig { @Bean public LocalEntityManagerFactoryBean entityManagerFactory() { LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean(); factoryBean.setPersistenceUnitName("StudentPU");
return factoryBean; }
@Bean public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager; } } |
Create Test Class
Create Test class named 'Test' to insert some sample data in the Student table.
Test.java
package com.java4coding;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(); appContext.scan("com.java4coding"); appContext.refresh();
StudentService studentService = (StudentService) appContext.getBean("studentService"); studentService.test();
appContext.close(); } } |
Output
Hibernate: insert into Student (firstName, lastName) values (?, ?) Hibernate: select student0_.id as id1_0_0_, student0_.firstName as firstNam2_0_0_, student0_.lastName as lastName3_0_0_ from Student student0_ where student0_.id=? Student [firstName=Manu, lastName=Manjunatha] Hibernate: select student0_.id as id1_0_, student0_.firstName as firstNam2_0_, student0_.lastName as lastName3_0_ from Student student0_ Student [firstName=Manu, lastName=Manjunatha] Hibernate: select count(*) as col_0_0_ from Student student0_ Number of students: 1 |
Now Check the Student Table, you can see data is stored in table.
Final Directory Structure of Project in eclipse
All Chapters