1. 程式人生 > >SpringBoot 整合Spring-Data-JPA

SpringBoot 整合Spring-Data-JPA

一、使用的工具:

1、JDK1.8

2、Eclipse

3、Maven

二、建立專案

1、建立SpringBoot專案

2、Maven 依賴配置如下:

<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>
  <parent>
    <groupId>com.zzg</groupId>
    <artifactId>SpringLearn</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>JPADemo</artifactId>
  <dependencies>
        <!-- spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- spring-boot-starter-data-jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <!--swagger setting-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- spring-boot-configuration-processor -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

SpringBoot 父類專案依賴配置檔案如下:

<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.zzg</groupId>
  <artifactId>SpringLearn</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.RELEASE</version>
  </parent>
  <modules>
  	<module>HikariCPDemo</module>
  	<module>JPADemo</module>
  </modules>
</project>

專案截圖如下:

包說明:

com.zzg.springboot.controller:控制層程式碼

com.zzg.springboot.entity:實體物件與資料庫表對於關係

com.zzg.springboot.repository:dao層介面定義

com.zzg.springboot.service:service 介面定義

cong.zzg.springboot.service.impl:service 介面實現類

com.zzg.springboot.swagger:swagger 配置屬性

四、程式碼實現

要求:基於mysql +jpa 構建簡單的查詢例項

4.1 entity 與table 對應關係

package com.zzg.springboot.entity;

import javax.persistence.*;

@Entity
@Table(name = "sys_user")
public class SysUser {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY) // id自動增長
	private Long id;
	private String username;
	private String password;

	public Long getId() {
		return id;
	}

	public void setId(Long 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;
	}
}

4.2 、dao 層介面定義:基於主鍵ID查詢

package com.zzg.springboot.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.zzg.springboot.entity.SysUser;

public interface SysUserRepository extends JpaRepository<SysUser, Long> {
}

4.3、service層介面定義和service層介面實現:基於主鍵ID查詢

package com.zzg.springboot.service;

import com.zzg.springboot.entity.SysUser;

public interface SysUserService {
	public SysUser findById(Long id);
}
package com.zzg.springboot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zzg.springboot.entity.SysUser;
import com.zzg.springboot.repository.SysUserRepository;
import com.zzg.springboot.service.SysUserService;

@Service
public class SysUserServiceImpl implements SysUserService {
	@Autowired
    private SysUserRepository repository;
	
	public SysUser findById(Long id) {
		// TODO Auto-generated method stub
		return repository.findOne(id);
	}

}

4.4、controller 層實現

package com.zzg.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zzg.springboot.entity.SysUser;
import com.zzg.springboot.service.SysUserService;

@RestController
@RequestMapping("/jpa")
public class JPAController {
	@Autowired
    private SysUserService service;
	
	@RequestMapping("/findById")
	public void findById() {
		SysUser bean = service.findById(1l);
		System.out.println("name is :" + bean.getUsername());
		System.out.println("password is :" + bean.getPassword());
	}

}

4.5、swagger 配置屬性

package com.zzg.springboot.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfigure {
	@Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zzg.springboot.controller"))
                .paths(PathSelectors.any())
                .build();
    }
	
	 private ApiInfo apiInfo() {
	        return new ApiInfoBuilder()
	                .title("Spring Boot中使用Swagger2構建RESTful APIs")
	                .description("Spring Boot Swagger2")
	                .termsOfServiceUrl("http://blog.csdn.net/zhouzhiwengang")
	                .contact("swagger")
	                .version("1.0")
	                .build();
	    }

}

4.6、程式入口

package com.zzg.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@EnableAutoConfiguration
@ComponentScan
@Configuration
public class Application {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SpringApplication.run(Application.class,args);
	}

}

五、建庫指令碼(sys_user)

CREATE TABLE `sys_user` (
	`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	`username` VARCHAR(200) NOT NULL COLLATE 'utf8mb4_general_ci',
	`password` VARCHAR(200) NOT NULL COLLATE 'utf8mb4_general_ci',
	PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3

今天就分享到這裡。