整合Spring Data JPA

本文讲解Spring Boot整合Spring Data JPA。

1 准备数据表

建立t_customer表

-- 创建客户表
CREATE TABLE t_customer(
   id INT PRIMARY KEY AUTO_INCREMENT,
   NAME VARCHAR(20),
   gender CHAR(1),
   telephone VARCHAR(20)
);

2 创建项目,导入依赖

<?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.yiidian</groupId>
    <artifactId>ch03_07_springboot_springdatajpa</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 导入springboot父工程. 注意:任何的SpringBoot工程都必须有的!!! -->
    <!-- 父工程的作用:锁定起步的依赖的版本号,并没有真正到依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.11.RELEASE</version>
    </parent>

    <dependencies>
        <!--web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- springBoot 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>
            <version>5.1.46</version>
        </dependency>
    </dependencies>
</project>

必须导入 Spring Data JPA的依赖!

3 编写Pojo,添加ORM映射

package com.yiidian.domain;

import javax.persistence.*;

/**
 * 实体类
 * 一点教程网 - www.yiidian.com
 */
@Entity
@Table(name="t_customer")
public class Customer {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private String gender;
	private String telephone;

	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 getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	@Override
	public String toString() {
		return "Customer{" +
				"id=" + id +
				", name='" + name + '\'' +
				", gender='" + gender + '\'' +
				", telephone='" + telephone + '\'' +
				'}';
	}
}

因为使用了Spring Data JPA,所以在Pojo实体中必须添加Jpa的映射注解,和数据库表进行一一映射。

4 编写Dao接口

package com.yiidian.dao;

import com.yiidian.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.util.List;

/**
 * Dao接口
 * 一点教程网 - www.yiidian.com
 */
public interface CustomerDao extends JpaRepository<Customer,Integer>,JpaSpecificationExecutor<Customer>{
}

Spring Data JPA提供了两个核心接口,我们项目中一般选择继承它们:

  • JpaRepository接口:拥有CRUD,分页,排序等方法
  • JpaSpecificationExecutor接口:拥有组合条件搜索方法

5 编写Controller

package com.yiidian.controller;
import java.util.ArrayList;
import java.util.List;

import com.yiidian.dao.CustomerDao;
import com.yiidian.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 控制器
 * 一点教程网 - www.yiidian.com
 */
@Controller
public class CustomerController {
	@Autowired
	private CustomerDao customerDao;

	/**
	 * 用户列表展示
	 */
	@RequestMapping("/list")
	@ResponseBody
	public List<Customer> list(){
		List<Customer> list = customerDao.findAll();
		return list;
	}
}

6 编写application.yml

内容如下:

spring:
  datasource: #修改数据库连接配置
    url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
# jpa配置
  jpa:
    show-sql: true #控制台输出生成的SQL语句
    generate-ddl: true # 自动建表

7 编写引导类

package com.yiidian;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * Spring Boot引导类
 * 一点教程网 - www.yiidian.com
 */
@SpringBootApplication
public class MyBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyBootApplication.class,args);
    }

}

8 运行测试

运行引导类,访问:http://localhost:8080/list

源码下载:https://pan.baidu.com/s/1LVsAktnj99tZCQrSkBUVng