1. 程式人生 > >springboot 整合 springdata

springboot 整合 springdata

        用膩了ssm,尤其是mybatis,每次使用者需求變動要求改表的時候都要刪掉各種實體類和mapper.xml然後再重新生成,所以最近小研究了一下springdata,demo框架:springboot + springdata

        首先是maven的pom.xml:

<?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>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</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>
        </dependency>


    </dependencies>

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


</project>

  springboot配置檔案:application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hrms?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database=mysql
#自動建表
spring.jpa.hibernate.ddl-auto=update
#設定資料庫方言
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
#列印sql
spring.jpa.show-sql=true

 spring.jpa.hibernate.ddl-auto配置自動建表,有四個屬性

        create:每次啟動時刪除表,再根據實體類建表

        create-drop:每次啟動時根據實體類建表,退出時刪表

        update:每次啟動時根據實體類更新表結構(表資料不變)

        validate:每次啟動時根據實體類校驗表結構

spring.jpa.database-platform配置資料庫方言

        如果你的實體類中有外來鍵,請配置此項,否則啟動報錯Specified key was too long; max key length is 1000 bytes,因為springdata預設的資料庫方言是org.hibernate.dialect.MySQL5Dialect,資料庫引擎是MyISAM,它既不支援高階事務也不支援外來鍵。

以簡單的系統管理為例,構建三個實體類UserEntity.java、RoleEntity.java、PermissionEntity.java:

UserEntity:

package com.example.demo.entity;

import javax.persistence.*;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName UserEntity
 * @Description TODO
 * @Author Rock-PC5
 * @Date 2018/9/19 13:45
 * @Version 1.0
 **/
@Entity
@Table(name = "user", schema = "hrms", catalog = "")
public class UserEntity {
	@Id
	@Column(name = "id")
	private String id;
	@Column(name = "username")
	private String username;
	@Column(name = "password")
	private String password;
	@ManyToMany
	@JoinTable(name = "user_role", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
	private Set<RoleEntity> roleEntitySet;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set<RoleEntity> getRoleEntitySet() {
		return roleEntitySet;
	}

	public void setRoleEntitySet(Set<RoleEntity> roleEntitySet) {
		this.roleEntitySet = roleEntitySet;
	}
}

 RoleEntity:

package com.example.demo.entity;

import javax.persistence.*;
import java.util.Set;

/**
 * @ClassName RoleEntity
 * @Description TODO
 * @Author Rock-PC5
 * @Date 2018/9/19 13:45
 * @Version 1.0
 **/
@Entity
@Table(name = "role", schema = "hrms", catalog = "")
public class RoleEntity {
	@Id
	@Column(name = "id")
	private String id;
	@Column(name = "name")
	private String name;
	@Column(name = "description")
	private String description;
	@ManyToMany(mappedBy = "roleEntitySet")
	private Set<UserEntity> userEntitySet;
	@ManyToMany
	@JoinTable(name = "role_permission", joinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "permission_id", referencedColumnName = "id")})
	private Set<PermissionEntity> permissionEntitySet;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set<UserEntity> getUserEntitySet() {
		return userEntitySet;
	}

	public void setUserEntitySet(Set<UserEntity> userEntitySet) {
		this.userEntitySet = userEntitySet;
	}

	public Set<PermissionEntity> getPermissionEntitySet() {
		return permissionEntitySet;
	}

	public void setPermissionEntitySet(Set<PermissionEntity> permissionEntitySet) {
		this.permissionEntitySet = permissionEntitySet;
	}
}

PermissionEntity:

package com.example.demo.entity;

import javax.persistence.*;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName PermissionEntity
 * @Description TODO
 * @Author Rock-PC5
 * @Date 2018/9/19 13:45
 * @Version 1.0
 **/
@Entity
@Table(name = "permission", schema = "hrms", catalog = "")
public class PermissionEntity {
	@Id
	@Column(name = "id")
	private String id;
	@Column(name = "name")
	private String name;
	@Column(name = "description")
	private String description;
	@ManyToMany(mappedBy = "permissionEntitySet")
	private Set<RoleEntity> roleEntitySet;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set<RoleEntity> getRoleEntitySet() {
		return roleEntitySet;
	}

	public void setRoleEntitySet(Set<RoleEntity> roleEntitySet) {
		this.roleEntitySet = roleEntitySet;
	}
}

簡單介紹一下其中的註解:

@Entity:指明該類是一個實體類

@Table:指明該類與表的對映關係

        name指明該類所對映的表名,如果不寫預設為類名

        schema指明該類所對映到的資料庫,如果不寫預設為連線到的資料庫名

        catelog的作用與schema一致

@Id:指明該屬性為主鍵

@Column:name指定該屬性所對應的欄位名

@ManyToMany:指明表間的多對多關係,mappedBy的作用是把維護表的任務交給與其關聯的實體類,值為與其關聯的實體類的對應外來鍵的引數名。除此之外還有@ManyToOne,@OneToMany,@OneToOne等。

@JoinTable:新建第三張關聯表來維護兩實體類的關聯關係

        name:新建表的表名

        joinColumns:該實體類對應表外來鍵的欄位名集合

        inverseJoinColumns:與其關聯的實體類對應表外來鍵的欄位名集合

@JoinColumn:新建表中新建的欄位

        name:新建的欄位名

        referencedColumnName:該欄位在主表中欄位名

然後啟動專案就可以了,生成的表如圖所示:

在初體驗springdata的時候,最直觀的感受就是專案目錄的簡潔,完全不需要那些dao、service以及然人看了想吐的mapper.xml,僅僅需要一個jpa即可操作一個實體類:

那jpa的程式碼如下:

UserJpa:

package com.example.demo.jpa;

import com.example.demo.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.io.Serializable;

/**
 * @ClassName UserJpa
 * @Description TODO
 * @Author Rock-PC5
 * @Date 2018/9/18 16:12
 * @Version 1.0
 **/
public interface UserJpa extends JpaRepository<UserEntity, String>, JpaSpecificationExecutor<UserEntity>, Serializable {

}

RoleJpa:

package com.example.demo.jpa;

import com.example.demo.entity.RoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.io.Serializable;

/**
 * @ClassName RoleJpa
 * @Description TODO
 * @Author Rock-PC5
 * @Date 2018/9/19 13:16
 * @Version 1.0
 **/
public interface RoleJpa extends JpaRepository<RoleEntity, String>, JpaSpecificationExecutor<RoleEntity>, Serializable {
}

PermissionJpa:

package com.example.demo.jpa;

import com.example.demo.entity.PermissionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.io.Serializable;

/**
*@author FastKing
*@Description 
*@Date 15:03 2018/9/19
*@Param 
*@return 
**/
public interface PermissionJpa extends JpaRepository<PermissionEntity, String>, JpaSpecificationExecutor<PermissionEntity>, Serializable {

}

你只需要繼承JpaRepository和JpaSpecificationExecutor,前者的第一個引數寫對應實體類,第二個引數寫對應實體類主鍵型別,後者的引數就是對應實體類

jpa的使用方法就和ssm中的service一樣,這裡給一個示例的Controller:

package com.example.demo.controller;

import com.example.demo.entity.UserEntity;
import com.example.demo.jpa.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName HelloController
 * @Description TODO
 * @Author FastKing
 * @Date 2018/9/13 9:02
 * @Version 1.0
 **/
@RestController
public class HelloController {

	@Autowired
	private UserJpa userJpa;

	@RequestMapping(value = "/login/{username}/{password}", method = RequestMethod.GET)
	public Object login(@PathVariable String username, @PathVariable String password) {
		UserEntity userEntity = new UserEntity();
		userEntity.setUsername(username);
		userEntity.setPassword(password);
		Example<UserEntity> userEntityExample = Example.of(userEntity);
		List<UserEntity> userList = userJpa.findAll(userEntityExample);
		return userList.size();
	}

	@RequestMapping(value = "/list")
	public Object list() {
		return userJpa.findAll();
	}
}

Example的用法可以類比Mybatis的xxxExample


更新一下三個實體類,

以UserEntity為例:

package com.example.demo.entity;

import javax.persistence.*;
import java.util.Set;

/**
 * @ClassName UserEntity
 * @Description TODO
 * @Author FastKing
 * @Date 2018/9/19 13:45
 * @Version 1.0
 **/
@Entity
@Table(name = "user", schema = "hrms", catalog = "")
public class UserEntity {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id" ,columnDefinition = ("int COMMENT 'id'"))
	private Integer id;
	@Column(name = "username" ,columnDefinition = ("varchar(255) COMMENT '使用者名稱'"))
	private String username;
	@Column(name = "password" ,columnDefinition = ("varchar(255) COMMENT '密碼'"))
	private String password;
	@Column(name = "salt",columnDefinition = ("varchar(255) COMMENT '鹽值'"))
	private String salt;
	@Column(name = "isLocked",columnDefinition = ("tinyint COMMENT '是否鎖定(0否1是)'"))
	private Byte isLocked;
	@Column(name = "isForbidden",columnDefinition = ("tinyint COMMENT '是否禁用(0否1是)'"))
	private Byte isForbidden;
	@ManyToMany
	@JoinTable(name = "user_role", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id",columnDefinition = ("int COMMENT '使用者id'"))}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id",columnDefinition = ("int COMMENT '角色id'"))})
	private Set<RoleEntity> roleEntitySet;

	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 getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set<RoleEntity> getRoleEntitySet() {
		return roleEntitySet;
	}

	public void setRoleEntitySet(Set<RoleEntity> roleEntitySet) {
		this.roleEntitySet = roleEntitySet;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}

	public Byte getIsLocked() {
		return isLocked;
	}

	public void setIsLocked(Byte isLocked) {
		this.isLocked = isLocked;
	}

	public Byte getIsForbidden() {
		return isForbidden;
	}

	public void setIsForbidden(Byte isForbidden) {
		this.isForbidden = isForbidden;
	}
}

@Column中的columnDefinition用來定義對應資料庫中的欄位型別和註釋,如果你要設定欄位型別為varchar必須指定長度,否則報sql語法錯誤

@GeteratedValue如果設定為auto,mysql會自動選擇squence自增策略,生成一個hibernate_squence表,用來記錄其他表的主鍵。由於mysql不支援這種自增策略,改為identity即可