ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Add a Database with JPA
    Java/Spring 2024. 10. 14. 00:42

    Spring Data JPA(Java Persistence API)에 대해 정리하였습니다.

     

     


    < What is Spring Data JPA? >

    Spring Data JPA is a library for Spring that helps to integrate a database into your REST API.

    Spring Data JPA is an abstraction layer that allows us to interact with objects in your code rather than write SQL queries.

     

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

    : To be able to use JPA in your project, you’ll have to add that dependency to your pom.xml

     

    [ JDBC vs JPA vs Spring Data JPA ]

    JPA stands for Java Persistence API, which is the underlying standard used to translate objects from Java into queries that can be sent directly to the underlying database.

    Spring Data JPA “wraps” around an implementation of the JPA to make it a seamless process to integrate a database into your Spring Boot Application.

    JPA does this by wrapping around another standard, JDBC (Java Database Connectivity). This is the layer that sends raw database queries to the underlying database.

    => JPA actually runs on top of JDBC, and actual query execution is done through JDBC.

     

     


    < Connecting to a Database >

    To connect to an embedded H2 using Spring Data JPA, we’ll need to update your application’s properties in properties file.

    When our Spring Boot application starts, it will check the properties file, located at src/main/resources/application.properties, for any information that it might require to configure our application correctly.

     

     

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </dependency>

    : To be able to use H2 in your project, you’ll have to add that dependency to your pom.xml

     

    The type of information that is typically stored inside properties files includes:
    - the database URL
    - the amount of logs your application should produce
    - the “port” your application runs on

     

    [ What is a H2? ]

    H2 is a relational database written entirely in Java.
    One convenient feature of H2 is that it can run on the same kind of infrastructure as your application and can run entirely “in-memory. This makes it easy to use to test your Spring Boot application on your machine, without having to obtain a database server from elsewhere for your application to use.

     

     


    < Create a Model >

    These Data objects, in this context, are referred to as models (or entities)
    a model corresponds to a
    table, and a field in a model corresponds to a column in that table

    use annotations to indicate how the model name and field names translate to the underlying table name and column names, respectively. 

     

    Example)

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Column;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="PEOPLE")
    public class Person {
    
        @Id
        @GeneratedValue
        private Integer id;
    
        @Column(name="NAME")
        private String name;
    
        @Column(name="AGE")
        private Integer age;
    
        @Column(name="EYE_COLOR")
        private String eyeColor;
    
    }
    • @Entity: tells the ORM that this model will be used to represent a table or relation in our database
    • @Table: tells the ORM what table name in the underlying database that this model corresponds to. 
    • @Id: tells the ORM that this field (id) will be used to uniquely identify a single entry in our "PEOPLE" relation
    • @GeneratedValue: tells the ORM that the developer will not be supplying the value for this field themselves. Instead, it should be “auto-generated” by the database. 
    • @Column: tells the ORM what column in the underlying relation that the annotated field corresponds to. For example, the eyeColor field of our entity corresponds to the "EYE_COLOR" column in the "PEOPLE" relation.

     

    +. When the ORM interacts with your model, it depends on getter and settermethods that have been appropriately named based on the fields. 

    @Column(name="AGE")
    private Integer age;
    
    public Integer getAge() {
      return this.age;
    }
    
    public void setAge(Integer age) {
      this.age = age;
    }

     

     


    < Create a Repository >

    Repository is a data access and manipulation layer that wraps around your data model.

    Repository will come with methods to call on instances of your data model like 
    .save(), or .findAll(), or .findById(), enabling a no-code solution to interacting with a data model in a Spring Boot application.

     

    Example)

    import org.springframework.data.repository.CrudRepository;
    import com.codecademy.people.entities.Person;
    
    // creating an extension of the CrudRepository that can manage our Person model
    public interface PersonRepository extends CrudRepository<Person, Integer> {
      // no method declarations are required! }

    : Some methods that the CrudRepository interface offers us to enable CRUD functionality are:

    • .findById(Integer id): allows you to query the database to find an instance of your model by its ID field
    • .findAll(): allows you to retrieve ALL the entries in the database for a given model
    • .save(Person p): allows you to create AND modify instances of your model in the database
    • .delete(Person p): allows you to delete instances of your model from the database

     

    [ Angle Brackets < > ]
    The angle brackets (< >) are a special kind of syntax used in Java to provide more specific type information to a class, using type parameters. You may have seen these used when we have a List of things in Java, like List<Integer>.

    In this example, the first type parameter is used to ensure that our PersonRepository knows it is responsible for managing instances of the
    Person object. The second type parameter is used to tell the repository the type of the ID field, which enables methods like .findById

     

     


    < Connect Your Repository to a Controller >

    The repository must be a dependency of the controller, and you can make the repository bean available to the controller class using dependency injection.

    To make a bean available to a class that depends on it, you can simply add it as a field of the class and include it in the constructor. 


     

    Example)

    import org.springframework.web.bind.annotation.RestController;
    import com.codecademy.people.repositories.PersonRepository;
    
    @RestController
    public class PersonController {
      private final PersonRepository personRepository;
    
      public PersonController(final PersonRepository personRepository) {
        this.personRepository = personRepository;
      }
    
      // ... all REST endpoint mappings
    }
    • Import the PersonRepository from the correct package
    • Add the PersonRepository as a field in the PersonController class
    • Add the PersonRepository to the constructor and assign it to the field appropriately

     

     


    < Get Data From Database : findAll(), findById() >

    Example)

    @RestController
    public class PersonController {
    
      private final PersonRepository personRepository;
    
      public PersonController(final PersonRepository personRepository) {
        this.personRepository = personRepository;
      }
    
      @GetMapping("/people")
      public Iterable<Person> getAllPeople() {
        return this.personRepository.findAll();
      }
    
      @GetMapping("/people/{id}")
      public Optional<Person> getPersonById(@PathVariable("id") Integer id) {
        return this.personRepository.findById(id);
      }
    
    }

     

     


    < Create a New Database Entry : save() >

    Example)

    @PostMapping("/people")
    public Person createNewPerson(@RequestBody Person person) {
      Person newPerson = this.personRepository.save(person);
      return newPerson;
    }

     

     


    < Update a Database Entry : save() >

    The .save() from the CrudRepository interface can be used both for creating new entries in the database as well as updating existing entries.

     

    Example)

    @PutMapping("/people/{id}")
    public Person updatePerson(@PathVariable("id") Integer id, @RequestBody Person p) {
      Optional<Person> personToUpdateOptional = this.personRepository.findById(id);
      if (!personToUpdateOptional.isPresent()) {
        return null;
      }
    
      // Since isPresent() was true, we can .get() the Person object out of the Optional
      Person personToUpdate = personToUpdateOptional.get();
    
      if (p.getName() != null) {
        personToUpdate.setName(p.getName());
      }
      if (p.getAge() != null) {
        personToUpdate.setAge(p.getAge());
      }
      if (p.getEyeColor() != null) {
        personToUpdate.setEyeColor(p.getEyeColor());
      }
    
      Person updatedPerson = this.personRepository.save(personToUpdate);
      return updatedPerson;
    }

     

     


    < Delete a Database Entry : delete() >

    Example)

    @DeleteMapping("/people/{id}")
    public Person deletePerson(@PathVariable("id") Integer id) {
      Optional<Person> personToDeleteOptional = this.personRepository.findById(id);
      if (!personToDeleteOptional.isPresent()) {
        return null;
      }
      Person personToDelete = personToDeleteOptional.get();
      this.personRepository.delete(personToDelete);
      return personToDelete;
    }

     

     

     

     

    'Java > Spring' 카테고리의 다른 글

    Spring Container & Bean  (3) 2024.12.12
    Object-Oriented Design and Spring  (46) 2024.11.19
    Custom Queries with JPA  (5) 2024.10.15
    Spring Controllers  (1) 2022.02.11
    Hello Spring  (2) 2022.02.10

    댓글

Designed by Tistory.