Java Persistence API with Spring Data
Let's try to build simple java application with the help of Spring Tool Suites IDE, Spring-Data connecting and MySql's relation database. You are free to choose any IDE (STS, Eclipse, Intellij etc). We are building simple application which is storing User information into MySQL Database table.
Our Requirements are simple
- IDE (any IDE, STS, Eclipse or Intellij)
- JDK 1.8 later
- Maven 3.2
Create a Maven project using spring initializr
Open the Spring Initializr (https://start.spring.io/ ). This is the best way to start the project. Type the https://start.spring.io on url browser The Initializr provides quick solution to place dependency and create project structure. Our requirement is JPA and MySql dependencies. below image shows the Initializr with required dependency selection:
Following pom.xml file will be generated having spring-boot-starter-data and mysql-connector-java dependency
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dimri</groupId>
<artifactId>jpaExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpaExample</name>
<description>Demo project for Spring Boot</description>
<properties><java.version>1.8</java.version></properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This java file is a JPA object annotation The following listing shows the User class. This is POJO (plain old java object) with JPA annotation.
package com.dimri.jpaExample.data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name="user_profile")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name = "firstName",length=50)
private String firstName;
@Column(name = "lastName",length=50)
private String lastName;
protected User() {} //Default constructor
//Parameterize constructor
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
The User.java file has three attributes: id,firstName and lastName. and we have two constructors. Default constructor for the JPA. Parameterize constructor will be used for instance creation. then saved into User table
This User class is annotated with @Entity(name="user") , So this entity is mapped with user table. The id property is annotated with @Id, JPA will mark it as object’s ID. The id is also annotated with @GeneratedValue. It will automatically generate the id.
Other properties are firstName ,lastName are annotated with @Column(name = "firstName",length=50) and @Column(name = "lastName",length=50) are mapped to columns that share the same names as the properties themselves.
Repository and Queries
Create the repository for the user table. Spring Data use repository to store data in MySql database. Spring Data has interesting feature feature to create repository implementations automatically from a repository interface.
To see how this works, create a repository interface that works with User entities as the following:
UserRepository extends the CrudRepository. CrudRepository is an interface The type of entity and ID that it works with, User and Long are declared in the generic parameters on CrudRepository. By extending CrudRepository UserRepository will inherits several methods
for working with User persistence , including methods for saving, deleting, and finding User entities.
package com.dimri.jpaExample.data;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByLastName(String lastName);
Optional<User> findById(Long id);
}
for working with User persistence , including methods for saving, deleting, and finding User entities.
Spring Data JPA also lets you define other query methods by declaring their method signature. For example,UserRepository includes the findByLastName() and findByFirstName() method.
Now you need to modify the simple class that the Initializr created for you. To get output (to the console, in this example), you need to set up a logger. Then you need to set up some data and use it to generate output.
The following listing shows the JpaExampleApplication class
package com.dimri.jpaExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.dimri.jpaExample.data.User;
import com.dimri.jpaExample.data.UserRepository;
@SpringBootApplication
public class JpaExampleApplication {
private static final Logger log = LoggerFactory.getLogger(JpaExampleApplication.class);
public static void main(String[] args) {
SpringApplication.run(JpaExampleApplication.class, args);
}
@Bean
public CommandLineRunner demo(UserRepository repository) {
return (args) -> {
// Save some user into database
repository.save(new User("Kailash", "Dimri"));
repository.save(new User("Jagmohan", "Negi"));
repository.save(new User("Harish", "Sharma"));
repository.save(new User("Ram", "Charan"));
repository.save(new User("Amit", "Verma"));
// fetch all Users
log.info("User found with findAll():");
log.info("-------------------------------");
for (User user : repository.findAll()) {
log.info(user.toString());
}
log.info("");
User user = repository.findById(1L).get(); // get user by ID
log.info("User found with findById(1L):");
log.info("--------------------------------");
log.info(user.toString());
log.info("");
log.info("User found with findByLastName('Dimri'):");
log.info("--------------------------------------------");
repository.findByLastName("Dimri").forEach(dimri -> {
log.info(dimri.toString());
}); // fetch user by last name
log.info("");
};
}
}
Build an executable JAR
It's almost done. Now you can run the application from the command line. You can build an executable JAR file that contains all the required dependencies, classes, and resources and run that.
You can build the jar file using maven using following command. If you are on spring tool suites editor. Just the application.
./mvnw clean package
./mvnw spring-boot:run
E:\blog\jpa-spring-data\jpaExample\target\jpaExample-0.0.1-SNAPSHOT.jar this is according to my setup. keep in mind that, jar file will be generated under target folder.
Last you can run the JAR file, as follows:
java -jar target/jpaExample-0.0.1-SNAPSHOT.jar
Later on you can validate it into database. login to mysql and execute the describe command. it will display the table structure. You can execute normal select command to check data inside the table.
When you run your application, you should see output similar to the following:
DESCRIBE user;
SELECT * from user;
if you need the source code. you can get it using the below link.
https://github.com/PersonSimple/jpaExample.git
Final
Congratulations! Work done.
Nicely explained
ReplyDelete