SpringBoot之使用jpa/hibernate

    Springboot版本是2.1.3.RELEASEjava

1、依賴

    List-1.1mysql

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</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>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.2</version>
</dependency>

2、項目總體結構

      

                                  圖2.1git

    bootstrap.yml內容以下,咱們不須要手動建立數據庫表,jpa/hiberate會自動會爲咱們建立的github

server:
  port: 9092
  servlet:
    context-path: /serviceB

spring:
  application:
    name: cat-service-b
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: ******
    url: jdbc:mysql://pig-mysql:3306/cat?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
    database: mysql
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
    show-sql: true
    properties:
      hibernate:
        format_sql: true

    physical-strategy的值爲org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy,那麼當實體的屬性爲駝峯結構時,對應到數據庫表的字段上,會用"_"隔開。web

3、代碼詳解

    List-3.1 BaseEntity的內容,全部的實體都要繼承這個類spring

import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.util.Date;

@Data
@MappedSuperclass
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;
    /** 建立人 */
    @CreatedBy
    protected String creator;
    /** 建立時間 */
    @CreatedDate
    protected Date createDate;
    /** 更新時間,默認是當前時間 */
    @LastModifiedDate
    protected Date updateDate = new Date();
    /** 狀態 0 表示刪除, 1表示可操做 */
    protected Integer status = 1;

    public BaseEntity() {
        if (null == this.id && null == this.createDate) {
            this.createDate = new Date();
        }
    }
}

    List-3.2 User的內容sql

import lombok.Data;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;

import javax.persistence.Entity;
import javax.persistence.Table;

@Data
@ToString

@Entity
@Table(name = "cat_user")
@SQLDelete(sql = "update cat_user set status = 0 where id = ?")
@Where(clause = "status <> 0")
public class User extends BaseEntity{
    private String name;
    private Integer age;
}

    List-3.3 UserRepository的內容數據庫

import com.mjduan.project.catserviceb.entity.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Integer> {

}

    List-3.4 UserController的內容bootstrap

import com.mjduan.project.catserviceb.entity.User;
import com.mjduan.project.catserviceb.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
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.RestController;

import java.util.Optional;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/queryUser/{id}")
    public User queryUser(@PathVariable(value = "id") Integer id) {
        log.info("查詢用戶,id={}", id);
        Optional<User> optionalUser = userRepository.findById(id);
        User user = optionalUser.isPresent() ? optionalUser.get() : null;
        log.info("返回,{}", user);
        return user;
    }

    @GetMapping(value = "/saveUser/{name}")
    public User saveUser(@PathVariable(value = "name") String name) {
        log.info("新增用戶,name={}", name);
        User user = new User();
        user.setAge(20);
        user.setName(name);
        User save = userRepository.save(user);
        log.info("返回,{}", save);
        return save;
    }
}

4、驗證

    在瀏覽器地址欄中輸入瀏覽器

    List-4.1

#保存name爲Tom的用戶
http://localhost:9092/serviceB/saveUser/Tom
#查詢Id爲1的用戶

http://localhost:9092/serviceB/queryUser/1

    

    一些思考:

  1. 自動建立表結構,咱們不須要手動去建立,咱們修改實體的時候,系統會自動更新數據庫中的表結構。
  2. 全部實體都繼承BaseEntity,那麼每一個實體對應的數據庫表,在建立日期、更新日期等共有屬性都同一了,這樣在必定程度上便於代碼理解和系統維護。

5、Reference

  1. Springboot配置mysql鏈接的部分配置參考:https://github.com/pristinecore/springbootsample/blob/master/springbootsample/src/main/resources/database.properties
  2. 格式化SQL輸出的參考:https://stackoverflow.com/questions/25720396/how-to-set-hibernate-format-sql-in-spring-boot
相關文章
相關標籤/搜索