1. 程式人生 > 其它 >spring boot——整合JPA——入門示例002

spring boot——整合JPA——入門示例002

pom檔案:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ch</groupId>
    <artifactId>ch6_1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ch6_1</name>
    <description>Demo project for
Spring Boot</description> <properties> <java.version>11</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-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 新增MySQL依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> <!-- MySQL8.x時,請使用8.x的聯結器 --> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

application.properties如下:

server.servlet.context-path=/ch6_1
###
##資料來源資訊配置
###
#資料庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?characterEncoding=utf8
#資料庫MySQL為8.x時,url為jdbc:mysql://localhost:3306/springbootjpa?useSSL=false&serverTimezone=Asia/Beijing&characterEncoding=utf-8
#資料庫使用者名稱 spring.datasource.username=root #資料庫密碼 spring.datasource.password=root #資料庫驅動 spring.datasource.driver-class-name=com.mysql.jdbc.Driver #資料庫MySQL為8.x時,驅動類為com.mysql.cj.jdbc.Driver #### #JPA持久化配置 #### #指定資料庫型別 spring.jpa.database=MYSQL #指定是否在日誌中顯示SQL語句 spring.jpa.show-sql=true #指定自動建立、更新資料庫表等配置,update表示如果資料庫中存在持久化類對應的表就不建立,不存在就建立對應的表 spring.jpa.hibernate.ddl-auto=update #讓控制器輸出的JSON字串格式更美觀 spring.jackson.serialization.indent-output=true

整體如下:

MyUser
package com.ch.ch6_1.entity;
import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_table")
/**
 * 如果沒寫表名,預設為類名的片語
 * (如MyUser類對應的表名為my_user)
 */
public class MyUser implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;//主鍵
    /**使用@Column註解,可以配置列相關屬性(列名,長度等),
     * 可以省略,預設為屬性名小寫
     */
    private String uname;
    private String usex;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getUsex() {
        return usex;
    }
    public void setUsex(String usex) {
        this.usex = usex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
UserRepository
package com.ch.ch6_1.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ch.ch6_1.entity.MyUser;
/**
 * 這裡不需要使用@Repository註解資料訪問層,
 * 因為Spring Boot自動配置了JpaRepository
 */
public interface UserRepository extends JpaRepository<MyUser, Integer>{
    public MyUser findByUname(String uname);
    public List<MyUser> findByUnameLike(String uname);
}
UserService
package com.ch.ch6_1.service;
import java.util.List;
import com.ch.ch6_1.entity.MyUser;
public interface UserService
{
    public void saveAll();
    public List<MyUser> findAll();
    public MyUser findByUname(String uname);
    public List<MyUser> findByUnameLike(String uname);
    public MyUser getOne(int id);
}
UserServiceImpl
package com.ch.ch6_1.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ch.ch6_1.entity.MyUser;
import com.ch.ch6_1.repository.UserRepository;
@Service
@Transactional
public class UserServiceImpl implements UserService{
    @Autowired
    private UserRepository userRepository;//依賴注入資料訪問層
    @Override
    public void saveAll() {
        MyUser mu1 = new MyUser();
        mu1.setUname("陳恆1");
        mu1.setUsex("男");
        mu1.setAge(88);
        MyUser mu2 = new MyUser();
        mu2.setUname("陳恆2");
        mu2.setUsex("女");
        mu2.setAge(18);
        MyUser mu3 = new MyUser();
        mu3.setUname("陳恆3");
        mu3.setUsex("男");
        mu3.setAge(99);
        List<MyUser> users = new ArrayList<MyUser>();
        users.add(mu1);
        users.add(mu2);
        users.add(mu3);
        //呼叫父介面中的方法saveAll
        userRepository.saveAll(users);
    }
    @Override
    public List<MyUser> findAll() {
        //呼叫父介面中的方法findAll
        return userRepository.findAll();
    }
    @Override
    public MyUser findByUname(String uname) {
        return userRepository.findByUname(uname);
    }
    @Override
    public List<MyUser> findByUnameLike(String uname) {
        return userRepository.findByUnameLike("%" + uname + "%");
    }
    @Override
    public MyUser getOne(int id) {
        //呼叫父介面中的方法getOne
        return userRepository.getOne(id);
    }

}
UserTestController
package com.ch.ch6_1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ch.ch6_1.service.UserService;
@Controller
public class UserTestController {
    @Autowired
    private UserService userService;
    @RequestMapping("/save")
    @ResponseBody
    public String save() {
        userService.saveAll();
        return "儲存使用者成功!";
    }
    @RequestMapping("/findByUname")
    public String findByUname(String uname, Model model) {
        model.addAttribute("title", "根據使用者名稱查詢一個使用者");
        model.addAttribute("auser", userService.findByUname(uname));
        return "showAuser";
    }
    @RequestMapping("/getOne")
    public String getOne(int id, Model model) {
        model.addAttribute("title", "根據使用者id查詢一個使用者");
        model.addAttribute("auser",userService.getOne(id));
        return "showAuser";
    }
    @RequestMapping("/findAll")
    public String findAll(Model model){
        model.addAttribute("title", "查詢所有使用者");
        model.addAttribute("allUsers",userService.findAll());
        return "showAll";
    }
    @RequestMapping("/findByUnameLike")
    public String findByUnameLike(String uname, Model model){
        model.addAttribute("title", "根據使用者名稱模糊查詢所有使用者");
        model.addAttribute("allUsers",userService.findByUnameLike(uname));
        return "showAll";
    }
}