SpringBoot系列之——整合JPA、mysql


一、JPA
      1. 概念:JPA顧名思義就是Java Persistence API的意思,是JDK 5.0注解或XML描述對象-關系表的映射關系,並將運行期的實體對象持久化到數據庫中。

      2.為什么 使用JPA:

        JPA 是 JCP 組織發布的 Java EE 標准之一,因此任何聲稱符合 JPA 標准的框架都遵循同樣的架構,提供相同的訪問API,這保證了基於JPA開發的企業應用能夠經過少量的修改就能夠在不同的JPA框架下運行。

a.容器級特性的支持

JPA框架中支持大數據集、事務、並發等容器級事務,這使得 JPA 超越了簡單持久化框架的局限,在企業應用發揮更大的作用。

b.簡單方便

JPA的主要目標之一就是提供更加簡單的編程模型:在JPA框架下創建實體和創建Java 類一樣簡單,沒有任何的約束和限制,只需要使用 javax.persistence.Entity進行注釋,JPA的框架和接口也都非常簡單,沒有太多特別的規則和設計模式的要求,開發者可以很容易的掌握。JPA基於非侵入式原則設計,因此可以很容易的和其它框架或者容器集成。

c.查詢能力

JPA的查詢語言是面向對象而非面向數據庫的,它以面向對象的自然語法構造查詢語句,可以看成是Hibernate HQL的等價物。JPA定義了獨特的JPQL(Java Persistence Query Language),JPQL是EJB QL的一種擴展,它是針對實體的一種查詢語言,操作對象是實體,而不是關系數據庫的表,而且能夠支持批量更新和修改、JOIN、GROUP BY、HAVING 等通常只有 SQL 才能夠提供的高級查詢特性,甚至還能夠支持子查詢。

d.高級特性

JPA 中能夠支持面向對象的高級特性,如類之間的繼承、多態和類之間的復雜關系,這樣的支持能夠讓開發者最大限度的使用面向對象的模型設計企業應用,而不需要自行處理這些特性在關系數據庫的持久化。

二、SpringBoot整合JPA
1.工程目錄

 

這里有個小坑,之前搞了半天發現自動生成不了實體類對應的表后來發現是包名的原因,這里要注意SpringbootJpaDemoApplication所在的包與entity所在包之間的關系,SpringbootJpaDemoApplication在com.example.demo中那么我們的實體類User就得在com.example.demo.Entity下,這樣才能成功對應生成實體類的表

2.配置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>

<groupId>com.example</groupId>
<artifactId>springboot-jpa-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-jpa-demo</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- jpa依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<!-- 熱部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- optional=true, 依賴不會傳遞, 該項目依賴devtools; 之后依賴boot項目的項目如果想要使用devtools, 需要重新引入 -->
<optional>true</optional>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

 

 


3.配置application.yml及application-test.yml

application.yml: (需注意配置格式)

spring:
profiles:
active: test
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: 123
jpa:
database: MYSQL
hibernate: 
ddl-auto: update
show-sql: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: UTC

 


 

 application-test.yml:

spring:
devtools:
restart:
enabled: true
additional-paths: src/main/java

 


我們的實體User類 :

package com.example.entity;

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

@Entity
@Table(name="t_user")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//自增
private Integer id;

private String name;

private String passWord;

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 String getPassWord() {
return passWord;
}

public void setPassWord(String passWord) {
this.passWord = passWord;
}
}

 


到這里,我們啟動項目,然后就會自動在數據庫中生成對應的t_user表

 

4.創建controller,service,dto做一些增刪改查的操作

a.controller:

package com.example.demo.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
@RestController
public class UserController {

@Autowired
IUserService userService;

@GetMapping(value="/getUserById")
public Optional<User> findUserById(@RequestParam("Id") Integer id){
return userService.findUserById(id);
}
@GetMapping("/all")
public List<User> findAll(){
return userService.findAll();
}

@PostMapping("/update")
public User updateUser(@RequestParam("Id") Integer id,@RequestParam("name") String name,@RequestParam("passWord") String passWord) {
return userService.updateUserById(id, name, passWord);
}

@PutMapping("/insert")
public User insertUser(@RequestParam("name") String name,@RequestParam("passWord") String passWord) {
return userService.insertUser(name, passWord);
}

@DeleteMapping("/delete")
public void deleteUser(@RequestParam("Id") Integer id) {
userService.deleteUserById(id);
}
}

 


b.service:

package com.example.demo.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.dto.IUserDto;
import com.example.demo.entity.User;
@Service
public class UserServiceImpl implements IUserService{

@Autowired
IUserDto iUserDto;

@Override
public Optional<User> findUserById(Integer id) {
return iUserDto.findById(id);
}

@Override
public User updateUserById(Integer id,String name, String passWord) {
User user = new User();
user.setId(id);
user.setName(name);
user.setPassWord(passWord);
return iUserDto.save(user);
}

@Override
public User insertUser(String name, String passWord) {
User user = new User();
user.setName(name);
user.setPassWord(passWord);
return iUserDto.save(user);
}

@Override
public void deleteUserById(Integer id) {
iUserDto.deleteById(id);
}

@Override
public List<User> findAll() {
return iUserDto.findAll();
}
}
c.dto:

package com.example.demo.dto;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.entity.User;

public interface IUserDto extends JpaRepository<User,Integer>{//默認傳的是ID為條件,如果需要其他條件來進行CRDU操作可通過增加方法來實現

public List<User> findByName(String name);//方法名不能亂寫,要按你需要的條件來寫 findBy你的字段名 
}

 

5.測試:

這里采用火狐的RESTClient

a.put用法

 

 b.delete用法

 

 c.post用法

 

d.Get用法


---------------------
作者:北半球先生
來源:CSDN
原文:https://blog.csdn.net/sinat_22808389/article/details/81592642


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM