2018/7/14

用Spring Boot使用JPA開發Restful Service

JPA是啥在這目前就不多說明,這篇要寫的是如何用Spring Boot使用JPA開發Restful Service
資料庫用的是MySQL
使用Spring Web MVC框架來開發Restful Service
具體要做的事情是寫一個Restful Service,用JPA對MySQL做資料的存取

pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>JPA</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
這裡記得一定要spring-boot-starter-data-jpa和mysql-connector-java這兩個函式庫

application.properties:
spring.datasource.url=jdbc:mysql://資料庫Server的IP:資料庫PORT號/要存取的資料庫名稱?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=資料庫帳號
spring.datasource.password=資料庫密碼
spring.jpa.properties.hibernate.id.new_generator_mappings=false
如果有讓程式去幫你建欄位的話,請把第四行換成spring.jpa.generate-ddl=true

創造JPA的實體類別Customer.java:
package com.example.demo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "firstname")
    private String firstName;
    @Column(name = "lastname")
    private String lastName;

    protected Customer() {
    }

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

    public Customer(Long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    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 String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}
注意@Entity這個標注,這是指名此類別為JPA的實體
@Table標註表示你要存取的資料表名稱
@Id標註表示將資料庫的primary key的欄位對應的這個屬性
@GeneratedValue標註將指定primary key產生的策略,這裡設為自動遞增
@Column標註表示將這個屬性對應到Column標註填寫的欄位名稱

補充:如果資料表名稱有大寫,就會出現以下的錯誤:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'dbB.tablea' doesn't exist
這隻程式跟這裡的程式不是同一個,而在這隻程式我在Table標注填入tableA,因為實際上資料表名稱是大寫,但他很像認不得資料表大寫名稱,所以出現這個錯誤,所以資料表名稱都先暫時取小寫就好。

創造CustomerRepository介面:
package com.example.demo;

import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
}
讓CustomerRepository去繼承CrudRepository,而這裡的的findByLastName就是我們自定義的method。
對於@Repository這個標注的說明,請看@Component and further stereotype annotations5.1.1. Spring Namespace,此標註與@Controller、@Component、@Service算是同一個層級的標注,而此標注的作用很像是作為例外處理的轉換之類的,主功能似乎沒影響,所以我有試過不標程式也可以work,不過依照官方的敘述,即使換成其他標注也可以動,但建議還是依照此類別的功能來給適當的標注比較好。

然後在MySQL建立一個資料表叫customer
和建立三個欄位分別為id、firstname、lastname,id為primary key並且為auto_increment,後面兩者的型態為varchar
那這裡先不寫用JPA建立欄位,因為目前還試不出來

新增資料:
package com.example.demo;

@RestController
@RequestMapping("/member")
public class WebController {

    @Autowired
    CustomerRepository repository;

    @RequestMapping(value = "/firstname/{firstName}/lastname/{lastName}", method = {RequestMethod.GET})
    @ResponseBody
    public String addPerson(@PathVariable String firstName, @PathVariable String lastName) {
        repository.save(new Customer(firstName, lastName));
        return firstName + " " + lastName;
    }
}
這裡用下面這個URL來新增一筆資料到資料庫
http://127.0.0.1:8085/kiki/member/firstname/Livio/lastname/Lorenzon
到資料庫查看:
可以發現已經存進去了,當然以Restful來說新增應該要用POST來新增比較符合原則,這裡只是為了示範用JPA的過程,就不照原則來寫了,有需要日後再自行更改。

查詢全部:
@RestController
@RequestMapping("/member")
public class WebController {

    @Autowired
    CustomerRepository repository;

    @RequestMapping(value = "/persons", method = {RequestMethod.GET})
    @ResponseBody
    public List<Customer> getAllPerson() {
        List<Customer> list = new ArrayList<>();
        for (Customer customer : repository.findAll()) {
            list.add(customer);
        }
        return list;
    }
}
以http://127.0.0.1:8085/kiki/member/persons網址來查詢,結果如下:

以ID來查詢:
@RestController
@RequestMapping("/member")
public class WebController {

    @Autowired
    CustomerRepository repository;
    
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public Customer getPersonId(@PathVariable Long id) {
        Optional<Customer> c = repository.findById(id);
        return c.get();
    }
}
查詢的網址為http://127.0.0.1:8085/kiki/member/26,回傳結果如下:
對於findById這個method,官方範例原本是這樣寫:
repository.findById(id).ifPresent((Customer customer) -> {
    logger.info(customer.toString());
});
但我沒辦法從裡面取customer這個物件,所以才改成上面那樣

以LastName來查詢:
@RestController
@RequestMapping("/member")
public class WebController {
    
    @Autowired
    CustomerRepository repository;

    @RequestMapping(value = "/lastName/{lastName}", method = {RequestMethod.GET})
    @ResponseBody
    public List<Customer> getPersonByLastName(@PathVariable String lastName) {
        List<Customer> list = new ArrayList<>();
        repository.findByLastName("Eastwood").forEach(customer -> {
            list.add(customer);
        });
        return list;
    }
}
以這個網址來查詢http://127.0.0.1:8085/kiki/member/lastName/Eastwood,結果如下:
這裡用的findByLastName method就是我們在CustomerRepository自己定義的查詢方法

最後附上完整的WebController程式:
package com.example.demo;

/*
Column都要小寫 https://github.com/babyachievement/notes/issues/20
Hibernate-sequence doesn't exist https://stackoverflow.com/questions/32968527/hibernate-sequence-doesnt-exist
 */
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/member")
public class WebController {

    Logger logger = LoggerFactory.getLogger(WebController.class);

    @Autowired
    CustomerRepository repository;

    @RequestMapping(value = "/firstname/{firstName}/lastname/{lastName}", method = {RequestMethod.GET})
    @ResponseBody
    public String addPerson(@PathVariable String firstName, @PathVariable String lastName) {
        repository.save(new Customer(firstName, lastName));
        return firstName + " " + lastName;
    }

    @RequestMapping(value = "/persons", method = {RequestMethod.GET})
    @ResponseBody
    public List<Customer> getAllPerson() {
        List<Customer> list = new ArrayList<>();
        for (Customer customer : repository.findAll()) {
            list.add(customer);
        }
        return list;
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public Customer getPersonId(@PathVariable Long id) {
        Optional<Customer> c = repository.findById(id);
        repository.findById(id).ifPresent((Customer customer) -> {
            logger.info(customer.toString());
        });
        return c.get();
    }

    @RequestMapping(value = "/lastName/{lastName}", method = {RequestMethod.GET})
    @ResponseBody
    public List<Customer> getPersonByLastName(@PathVariable String lastName) {
        List<Customer> list = new ArrayList<>();
        repository.findByLastName(lastName).forEach(customer -> {
            list.add(customer);
        });
        return list;
    }
}

至於CrudRepository這個類別的原始碼如下:
package org.springframework.data.repository;

import java.util.Optional;

@NoRepositoryBean
public interface CrudRepository<T extends Object, ID extends Object> extends Repository<T, ID> {

    public <S extends T> S save(S s);

    public <S extends T> Iterable<S> saveAll(Iterable<S> itrbl);

    public Optional<T> findById(ID id);

    public boolean existsById(ID id);

    public Iterable<T> findAll();

    public Iterable<T> findAllById(Iterable<ID> itrbl);

    public long count();

    public void deleteById(ID id);

    public void delete(T t);

    public void deleteAll(Iterable<? extends T> itrbl);

    public void deleteAll();
}
所以save和findById都是它提供的方法,根據文件似乎也可以覆寫它們:


參考資料:
Spring Data JPA - Reference Documentation

沒有留言:

張貼留言