Sitemap
Vikram

Vikram

SPRING DATA JPA

6 min readJun 18, 2020

--

What is JPA?

JPA, short for the Java Persistence API, is a Java API that maps data from the database into an object in the Java language, reducing the burden of coding and making database management more efficient. Between the Object Model and the Relation Model.

Press enter or click to view image in full size

The ability of JPA is to extract data from the Database and convert it into an Object of the Java language and can convert the Object of the Java language into Database data. This is a benefit of JPA that programmers do not need to write a Query Statement to handle. Chilling information Even if you rely on the capabilities of the IDE, then Generate it for just a moment.

Want to use JPA, what to do?

Because JPA is an API (Application Programming Interface), Inteface is not yet available! Must implement first. Therefore, if we want to try What makes me happy is to find a good provider. Currently, there are many providers to implement such as Hibernate, Eclipselink, Spring Data JPA, etc. Each has its advantages and disadvantages as normal. However, try to study and choose the most suitable for the job

Spring Data JPA

If we want to call spring data jpa, we have to call through the Query method interface that JPA implements for us. findByFirstnameOrderByCreateDateDesc Refers to extract data from Column Name = firstname by extracting and creating with Desc CreateDate.

So it works like this when compared to Query SQL.

Press enter or click to view image in full size
Press enter or click to view image in full size
  • find = is a search for information similar to the selection in the Database
  • By = is a filter that needs to be similar to where in a Database
  • OrderBy … Asc, OrderBy … Desc = is a sorting of data similar to ordering by objects in the database.

The good thing about it is that we can write it in human language to retrieve the data and it provides a lot of interface. Makes it easy to run

Start using Spring Data JPA.

We will use Spring Initializr to build our project, create a project and choose dependencies as follows:

  • Web is a Starter dependency for creating a web site that includes RESTful, Spring MVC and embedded tomcat by default.
  • JPA (Java Persistence API)
  • H2, we will use H2 which is in memory database.
  • Lombok, which is an annotation processing, helps code generation, such as reducing Getter Setter by adding annotation instead.

After selecting the dependencies, you can click the Generate Project button.

Press enter or click to view image in full size
Press enter or click to view image in full size

Spring Initializr will load the file to us about this.

Once done, you can insert the file into our project. Here, we can use the Spring Data JPA.

Get Vikram’s stories in your inbox

Join Medium for free to get updates from this writer.

In the Spring Initializr file that Generate for you will include the dependencies we have chosen as follows:

Dependencies

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Config port

Corrected the new port to 9090.

server.port = 9090
spring.application.name = demoservice

Person Entity

Create a Class Person and add the JPA annotations as follows.

  • @Entity is to define a class as an entity.
  • @Id is the assignment of the primary key of the entity
  • @GeneratedValue Tells the generation values ​​for the primary key. GenerationType.AUTO means time inert new data. The system will generate the id automatically.
  • @Column is used to specify the name of the columns in our tables.
  • @Getter @Setter is set to get get set. We do not need to create our own dependencies. Lombok is our handle.
@Entity
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
private long id;

@Getter @Setter
private String firstName;

@Getter @Setter
private String lastName;

protected Person() {}

public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

@Override
public String toString() {
/*
* return String.format( "Person[id=%d, firstName='%s', lastName='%s']"
* , id, firstName, lastName);
*/
return String.format("%d = %s %s", id, firstName, lastName);
}
}

MemberRepo

Then create PersonRepository as follows

  • findByFirstName => … where firstname =? 1
  • findByLastName => … where lastname =? 1
  • findByFirstNameOrLastName => … where firstname =? 1 or lastname =? 2
  • findByFirstNameOrLastName => … where firstname =? 1 and lastname =? 2
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

List<Person> findByFirstName(@Param("name") String name);
List<Person> findByLastName(@Param("name") String name);

List<Person> findByFirstNameOrLastName(@Param("fname") String firstName,@Param("lname") String lastName);
List<Person> findByFirstNameAndLastName(@Param("fname") String firstName,@Param("lname") String lastName);

}

DemoApplication adds CommandLineRunner

Below is a simple code that uses CommandLineRunner. Bean uses CommandLineRunner. Will work immediately after the Spring application context has been initialized. We create a bean using CommandLineRunner and Save Data to the DB to have data for browsing.

@SpringBootApplication
public class DemoApplication {
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@Bean
public CommandLineRunner demo(PersonRepository repository) {
return (args) -> {

// save a couple of customers
repository.save(new Person("Jack", "Bauer"));
repository.save(new Person("Chloe", "O'Brian"));
repository.save(new Person("Kim", "Bauer"));
repository.save(new Person("David", "Palmer"));
repository.save(new Person("Michelle", "Dessler"));

// fetch all customers
log.info("Person found with findAll():");
log.info("-------------------------------");
for (Person person : repository.findAll()) {
log.info(person.toString());
}
log.info("-------------------------------");
};
}
}

Maincontroller

Create a MainController In order to be able to use the web via Rest api.

Which has method to call, call as follows

  • home () for accessing the first page of the website on what to show
  • showAllPerson () for showing all Person data in the DB
  • searchPerson () for search FirstName = ‘David’ or LastName = ‘David’
  • insertPerson () for inserting Person Name = ‘Kim Jisoo’
  • deletePerson () for deleting Person Name = ‘Jack Bauer’
@Controller
public class MainController {

@Autowired
private PersonRepository personRepository;

@ResponseBody
@RequestMapping("/")
public String home() {
String html = "";
html += "<ul>";
html += " <li><a href='/showAllPerson'>Show All Person</a></li>";
html += " <li><a href='/searchPerson'>Search Person Name = 'David'</a></li>";
html += " <li><a href='/insertPerson'>Insert Person Name = 'Kim Jisoo'</a></li>";
html += " <li><a href='/deletePerson'>Delete Person Name = 'Jack Bauer'</a></li>";
html += "</ul>";
return html;
}

@ResponseBody
@RequestMapping("/showAllPerson")
public String showAllPerson() {
Iterable<Person> person = this.personRepository.findAll();

String html = "";
if (person != null) {
for (Person emp : person) {
html += emp + "<br>";
}
}
html += "<br><a href='/'>Back To Home Page</a>";
return html;
}

@ResponseBody
@RequestMapping("/searchPerson")
public String searchPerson() {
String html = "Test Search Person Name = 'David'<br>";
List<Person> person = this.personRepository.findByFirstNameOrLastName("David", "David");

if (person != null) {
for (Person emp : person) {
html += emp + "<br>";
}
}
html += "<br><a href='/'>Back To Home Page</a>";
return html;
}

@ResponseBody
@RequestMapping("/insertPerson")
public String insertPerson() {
String html = "Test Insert Person Name = 'Kim Jisoo'<br>";
Person person = new Person("Kim", "Jisoo");
this.personRepository.save(person);
html += "Inserted: " + person + "<br><br><a href='/'>Back To Home Page</a>";
return html;
}

@ResponseBody
@RequestMapping("/deletePerson")
public String deletePerson() {
String html = "Test delete Person Name = 'Jack Bauer'<br>";
List<Person> person = this.personRepository.findByFirstNameAndLastName("Jack", "Bauer");
if (person != null && !person.isEmpty()) {
//this.personRepository.deleteById(person.get(0).getId());
this.personRepository.delete(person.get(0));
}
html += "Deleted: 'Jack Bauer' <br><br><a href='/'>Back To Home Page</a> <br><br>";
return html;
}
}

Test

Run the application. The system will print the Person data that we initialized from Method CommandLineRunner in Class DemoApplication.

Press enter or click to view image in full size

Enter the page via link => http: // localhost: 9090 /

You can download the code from here to try it immediately.

Link: https://github.com/vikramjitsaha/poc/blob/master/spring-data-jpa-master.zip

--

--