spring boot——整合JPA——入門示例001
阿新 • • 發佈:2022-05-29
需要新增的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
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 https://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.2.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mohai.one</groupId> <artifactId>springboot-data-jpa</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-data-jpa</name> <description>spring-data-jpa整合實現</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
application.yml配置資訊:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/mohai_demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull username: root password: 123456 # JPA配置 jpa: # 資料庫型別 database: mysql # 切換預設的儲存引擎切換為InnoDB database-platform: org.hibernate.dialect.MySQL5InnoDBDialect # 輸出日誌中打印出執行的SQL語句 show-sql: true # 配置程式在啟動的時候自動操作實體類對應的表 hibernate: #create:程式重新啟動時,都會重新建立表,會造成資料會丟失 #create-drop:每次執行程式時,會先建立表結構,然後待程式結束時清空表 #upadte:每次執行程式時,實體對應沒有表時會建立表,如果實體發生改變會更新表結構,原來資料不會清空只會更新 #validate:每次執行程式時,會校驗資料與資料庫的欄位型別是否相同 ddl-auto: update
UserEntity類
package com.mohai.one.springbootjpa.domain; import javax.persistence.*; @Entity //必選註解,宣告和資料庫中user表關聯 @Table(name = "user") //可選註解,宣告實體對應的表資訊 public class UserEntity { @Id // 表名實體唯一標識 @GeneratedValue(strategy = GenerationType.IDENTITY) //主鍵自動生成策略 private Integer id; //@Column定義列名和屬性,預設為欄位名 @Column private String name; @Column private int age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserRepository
package com.mohai.one.springbootjpa.repository; import com.mohai.one.springbootjpa.domain.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserRepository extends JpaRepository<UserEntity,Integer> { List<UserEntity> findAllByName(String name); @Modifying @Query(value = "insert into user(id,name,age) values(:id,:name,:age)",nativeQuery = true) int insertNameAndAge(@Param("id") Integer id, @Param("name") String name, @Param("age") int age); }
UserService
package com.mohai.one.springbootjpa.service; import com.mohai.one.springbootjpa.domain.UserEntity; import com.mohai.one.springbootjpa.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @Service public class UserService { @Autowired private UserRepository userRepository; //查 public List<UserEntity> getAll(){ return userRepository.findAll(); } //查 public List<UserEntity> findAllByName(String name){ return userRepository.findAllByName(name); } //通過id查詢 public UserEntity getOne(Integer id){ return userRepository.findById(id).get(); } //改 @Transactional public UserEntity updateUser(UserEntity userEntity){ return userRepository.saveAndFlush(userEntity); } //增 @Transactional public int insertUser(UserEntity userEntity){ return userRepository.insertNameAndAge(userEntity.getId(),userEntity.getName(),userEntity.getAge()); } //刪 @Transactional public void deleteUserById(Integer id){ userRepository.deleteById(id); } }
UserController
package com.mohai.one.springbootjpa.controller; import com.mohai.one.springbootjpa.domain.UserEntity; import com.mohai.one.springbootjpa.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @Created by [email protected] */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/findAll") public List<UserEntity> findAll(){ return userService.getAll(); } @RequestMapping("/findAllByName") public List<UserEntity> findAllByName(String name){ return userService.findAllByName(name); } //通過主鍵Id查詢 @RequestMapping("/getOne/{id}") public UserEntity getUserById(@PathVariable Integer id){ return userService.getOne(id); } @RequestMapping("/save") public int save(@RequestBody UserEntity userEntity){ return userService.insertUser(userEntity); } @RequestMapping("/edit") public UserEntity edit(@RequestBody UserEntity userEntity){ return userService.updateUser(userEntity); } @RequestMapping("/delete") public int delete(@RequestParam("id") Integer id){ userService.deleteUserById(id); return 1; } }