1. 程式人生 > >31 SpringBoot與JPA整合

31 SpringBoot與JPA整合

jpa維護困難,不建議使用(個人拙見)

1 依賴匯入

<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-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId
>
mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>

2 實體類

package com.gp6.springboot26.bean;

import javax.persistence.*;

/*
    使用JPA註解配置對映關係
        @Entity : 告訴JPA這是一個實體類(和資料表對映的類)
        @Table  : 來指定和哪個資料表對應;如果省略預設表名就是user
        @Id     : 標明主鍵
 */
@Entity @Table(name = "m_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主鍵 private Integer id; // 和資料表對應的一個列 @Column(name = "user_name",length = 50) private String userName; // 省略,預設列名就是屬性名 @Column private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }

3 application.properties

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# update: 更新或建立  資料表結構
# 在專案啟動時,會在資料庫中根據實體類自動生成或更新表
spring.jpa.hibernate.ddl-auto=update

# 控制檯顯示SQL
spring.jpa.show-sql=true

4 Controller

package com.gp6.springboot26.controller;

import com.gp6.springboot26.bean.User;
import com.gp6.springboot26.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
		// getOne查詢結果為null,原因未知
        User user1 = userRepository.getOne(id);
        Optional<User> user = userRepository.findById(id);	
        return user.get();
    }

    @PostMapping("/user")
    public User insertUser(User user){
        User save = userRepository.save(user);
        return save;
    }

}