Spring Boot笔记-Spring Boot与数据访问(六)

对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种xxxTemplate,xxxRepository来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。我们将在数据访问章节测试使用SQL相关、NOSQL在缓存、消息、检索等章节测试。

1.JDBC

创建Spring Boot项目,加入依赖的时候,勾选Spring Web、JDBC API、MySQL Driver。开启虚拟机,并启动MySQL的docker镜像,使用Navicat测试是否可以连接成功。

编写application.yml配置文件。

高版本的MySQL在写url的时候需要带上时区等参数,否则连接的时候会报错,关于driver-class-name的问题,如果使用的是驱动是mysql-connector-java 5,就用com.mysql.jdbc.Driver,如果使用的是mysql-connector-java 6,就用com.mysql.cj.jdbc.Driver。

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.0.123:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    initialization-mode: always # 启动Spring Boot项目主程序启动的时候,执行初始化方法

通过测试类测试配置是否正确,Spring Boot 1.x的数据源默认是org.apache.tomcat.jdbc.pool.DataSource,Spring Boot 2.x改成了com.zaxxer.hikari.HikariDataSource。因为HikariDataSource更高效。

package com.atguigu.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class SpringBoot06DataJdbcApplicationTests {
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

自动配置原理:查看org.springframework.boot.autoconfigure.jdbc下的代码。

1.默认支持的数据源

打开DataSourceConfiguration类,通过注解的判断,自动注入的DataSource。默认支持org.apache.commons.dbcp2.BasicDataSource、com.zaxxer.hikari.HikariDataSource、org.apache.tomcat.jdbc.pool.DataSource。

2.自定义数据源

也可以在配置文件中,使用spring.datasource.type来手动指定。通过DataSourceBuilder类的build()方法,通过反射创建数据源。

3.DataSourceInitializer

查看DataSourceInitializer类的getScripts()方法,这个方法在Spring Boot项目启动的时候,会扫描类路径下有没有schema-*.sql或data-*.sql文件,如果有,就执行里面的SQL语句。

private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {
    if (resources != null) {
        return this.getResources(propertyName, resources, true);
    } else {
        String platform = this.properties.getPlatform();
        List<String> fallbackResources = new ArrayList();
        fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
        fallbackResources.add("classpath*:" + fallback + ".sql");
        return this.getResources(propertyName, fallbackResources, false);
    }
}

我们可以在类路径下,创建一个schema-all.sql文件,添加建表语句,在配置文件中加入initialization-mode: always,再启动项目,可以发现在数据库里创建了一张表。

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

如果在初始化的时候,需要执行多条SQL,并且这些SQL位于不同的文件中,可以在配置文件中指定这些schema,比如,我有两个SQL需要执行:department.sql和employee.sql。可以在配置文件中加入下面的内容,就可以初始化的时候,运行这些SQL。

spring:
  datasource:
    schema: classpath:department.sql, employee.sql

4.测试JDBC

注释掉配置文件中的初始化相关内容,在数据库中加入几条数据,编写Controller,发送请求获取数据。

package com.atguigu.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/query")
    public Map<String, Object> query() {
        return jdbcTemplate.queryForList("SELECT * FROM department LIMIT 1").get(0);
    }
}

2.整合Druid数据源

视频中讲解的内容是Spring Boot 1.x版本的,做一下记录,了解一下,后面的是Spring Boot 2.x版本的。

1.Spring Boot 1.x版本

pom文件中加入Druid依赖。

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

修改application.yml,指定数据源,也就是type的值。再加入一些DataSource的配置。

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.0.123:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    
    # 数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

    # initialization-mode: always # 启动Spring Boot项目主程序启动的时候,执行初始化方法
    # schema: classpath:department.sql, classpath:employee.sql

继续运行测试类,发现数据源已经由原来默认的HikariDataSource变为DruidDataSource了。在配置数据源的时候,通常还需要指定其他参数,这里需要些一个配置类DruidConfig.java,用于读取配置文件中的内容,否则,设置不进去。

package com.atguigu.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    // 配置Druid的监控
    // 1.配置管理后台的Servlet
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        Map<String, String> map = new HashMap<String, String>();
        map.put("loginUsername", "root");// 后台监控的用户名
        map.put("loginPassword", "root");// 后台监控的密码
        map.put("allow", "");// 默认允许所有访问
        map.put("deny", "127.0.0.1");// 把本机ip设置成拒绝访问用于测试,在访问的时候也要用127.0.0.1,不能用localhost
        // 访问http://127.0.0.1:8080/druid,会提示“Sorry, you are not permitted to view this page.”
        servletRegistrationBean.setInitParameters(map);
        return servletRegistrationBean;
    }

    // 2.配置一个web监控的Filter
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map<String, String> map = new HashMap<String, String>();
        map.put("exclusions", "*.js,*.css,/druid/*");
        filterRegistrationBean.setInitParameters(map);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        return filterRegistrationBean;
    }
}

访问http://127.0.0.1:8080/druid,输入账号密码,就可以登陆到Druid的后台监控了。

2.Spring Boot 2.x版本

引入Druid的依赖,这里的依赖是starter的形式。

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

 修改yml文件,添加DataSource的配置,可以和上面的Spring Boot 1.x对比下,其实没什么差别,这么做的好处是不需要写DruidConfig类了,需要的配置,都在yml里写好即可。

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.0.123:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # Druid数据源配置
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 300000
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      max-pool-prepared-statement-per-connection-size: 20
      use-global-data-source-stat: true
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      # 之前在servletRegistrationBean里设置的参数
      stat-view-servlet:
        login-username: root
        login-password: root
        deny: 127.0.0.1
      # 之前在filterRegistrationBean里设置的参数
      web-stat-filter:
        exclusions: "*.js,*.css,/druid/*"
  # initialization-mode: always # 启动Spring Boot项目主程序启动的时候,执行初始化方法
  # schema: classpath:department.sql, classpath:employee.sql

可以发现Spring Boot 2.x版本更加简单了。

3.整合Mybatis

创建Spring Boot项目,添加Spring Web、JDBC API、Mybatis Framework、MySQL Driver依赖。新建一个mybatis数据库,添加yml配置文件对Druid进行配置,这里采用Spring Boot 2.x的方式了,因为这样比较简单。

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.0.123:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # Druid数据源配置
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 300000
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      max-pool-prepared-statement-per-connection-size: 20
      use-global-data-source-stat: true
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      # 之前在servletRegistrationBean里设置的参数
      stat-view-servlet:
        login-username: root
        login-password: root
        deny: 127.0.0.1
      # 之前在filterRegistrationBean里设置的参数
      web-stat-filter:
        exclusions: "*.js,*.css,/druid/*"

在mybatis数据库里创建department和employee两张表,用于测试。创建对应的JavaBean。

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1.注解版

编写DepartmentMapper.java和DepartmentController用于测试。

package com.atguigu.springboot.controller;

import com.atguigu.springboot.bean.Department;
import com.atguigu.springboot.mapper.DepartmentMapper;
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;

@RestController
public class DepartmentController {
    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("/department/{id}")
    public Department getDepartment(@PathVariable("id") int id) {
        return departmentMapper.getDepartmentById(id);
    }

    @GetMapping("/department")
    public Department insertDepartment(Department department) {
        departmentMapper.insertDepartment(department);
        return department;
    }
}

发送请求http://localhost:8080/department?departmentName=AA会往数据库里插入一条Department记录,再请求http://localhost:8080/department/1,就能得到刚才的那条记录。

package com.atguigu.springboot.mapper;

import com.atguigu.springboot.bean.Department;
import org.apache.ibatis.annotations.*;

@Mapper
public interface DepartmentMapper {
    @Select("SELECT * FROM department where id = #{id}")
    public Department getDepartmentById(int id);

    @Delete("DELETE FROM department where id = #{id}")
    public int deleteDepartmentById(int id);

    // 表示使用自动生成的主键,主键对应的字段是id,在执行插入操作后,会将id进行返回
    // 注意,这里的返回是指封装到department里面,而不是作为方法的返回值,方法的返回值是1代表,此次SQL对表的影响行数是1
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("INSERT INTO department(departmentName) VALUES (#{departmentName})")
    public int insertDepartment(Department department);

    @Update("UPDATE department SET departmentName = #{departmentName} WHERE id = #{id}")
    public int updateDepartment(Department department);
}

到这里,提一句mybatis里的知识点。

在发送http://localhost:8080/department?departmentName=AA请求的时候,会把departmentName作为参数传给insertDepartment()方法,但是insertDepartment()方法接收的是Department类型的参数,这时候Mybatis会帮我们调用setDepartmentName()方法把传过来的departmentName给赋值进去,因为没有传id,所以id取默认值0,然后调用Mapper的时候,传递的也是department对象,并且这个对象只有departmentName属性。

再看DepartmentMapper里面,@Insert里面直接取的departmentName,此时会调用department.getDepartMent()方法获取值。

假设在Mapper的某个方法里面,只有一个基本类型的参数id,那么在SQL上取参数,就使用#{id}的方式即可。

@Select("SELECT * FROM table WHERE id = #{id}")
public void fun(int id);

假设在Mapper的某个方法里面,只有一个引用类型的参数,也就是只有一个对象,那么在SQL上取参数的,直接使用属性取值,比如这里的#{id},这里直接用属性即可,因为只有一个对象参数。如果,在Mapper接口的参数上带了@Param("department"),那么这里就不能直接使用#{id}了,必须使用#{department.id}才行。

@Select("SELECT * FROM table WHERE id = #{id}")
public void fun(Department department);
或
@Select("SELECT * FROM table WHERE id = #{department.id}")
public void fun(@Param("department") Department department);

假设在Mapper的某个方法里面,有多个参数(不管是基本类型还是引用类型)的时候,必须在Mapper接口上给每个参数带上@Param("key")的注解,这些key就是在SQL中的标识,Mybatis是通过@Param里指定的key找到对应的参数,这里又要分两种情况。

假设这个@Param标注的参数是基本类型id,那么在SQL里,直接使用#{id}即可。

假设这个@Param标注的参数是引用类型department,那么在SQL里,需要使用#{department.departmentName}来获取属性值,这里的department是要带着的。

@Select("SELECT * FROM table WHERE id = #{id} AND departmentName = #{department.departmentName}")
public void fun(@Param("department") Department department, @Param("id") int id);

通常,数据库里的字段是小写加下划线分隔的,JavaBean里是驼峰命名法,会出现对应不上的情况,如果采用配置文件的方式,可以修改配置文件将驼峰命名和下划线命名匹配。

<!--开启驼峰命名法和下划线命名法的匹配-->
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

如果没有配置文件呢?查看MybatisAutoConfiguration类的applyConfiguration()方法,里面有一个ConfigurationCustomizer类用于自定义设置的。我们可以自己写一个ConfigurationCustomizer类,将自定义的设置添加进去,这里就是给mapUnderscoreToCamelCase属性赋值,最后把ConfigurationCustomizer注入到容器中。

package com.atguigu.springboot.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

测试发现,从数据库获取的department_name也可以映射到JavaBean里的departmentName了,说明自定义配置生效了。

另外再提一句,一种更简便的方式,也就是在yml里做配置。

mybatis:
  configuration:
    map-underscore-to-camel-case: true

在后序的开发中,可能会有很多的Mapper文件,如果在每个Mapper文件上都标注@Mapper,就是一个重复的工作,于是,我们可以使用一个新的注解,减少这种工作量。这个注解要加在项目的主启动类上,代表在项目启动的时候,就指明了mapper文件的位置,

package com.atguigu.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan(value = "com.atguigu.spring.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
    }
}

2.配置文件版

创建EmployeeMapper.java。

package com.atguigu.springboot.mapper;

import com.atguigu.springboot.bean.Department;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmployeeMapper {
    public Department getEmployeeById(int id);

    public int insertEmployee(Department department);
}

在resources下创建mybatis文件夹,放入mybatis-config.xml全局配置文件,在mybatis文件夹下创建mapper文件夹,用来存放SQL。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springboot.mapper.EmployeeMapper">
    <select id="getEmployeeById" resultType="com.atguigu.springboot.bean.Employee">
        SELECT * FROM employee WHERE id = #{id}
    </select>

    <insert id="insertEmployee">
        INSERT INTO employee(lastName, email, gender, d_id) VALUES (#{lastName}, #{email}, #{gender}, #{dId})
    </insert>
</mapper>

在yml下对指定mybatis全局文件的位置和mapper文件的位置。如果还需要在yml里配置其他参数,参照官网:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

编写EmployeeController.java进行测试。

package com.atguigu.springboot.controller;

import com.atguigu.springboot.bean.Employee;
import com.atguigu.springboot.mapper.EmployeeMapper;
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;

@RestController
public class EmployeeController {
    @Autowired
    EmployeeMapper employeeMapper;

    @GetMapping("/employee/{id}")
    public Employee getDepartment(@PathVariable("id") int id) {
        return employeeMapper.getEmployeeById(id);
    }

    @GetMapping("/employee")
    public Employee insertDepartment(Employee employee) {
        employeeMapper.insertEmployee(employee);
        return employee;
    }
}

在数据库里加入一条记录,发送http://localhost:8080/employee/1请求,可以拿到数据库中刚刚添加的那条记录,测试通过。

4.整合Spring Data JPA

1.Spring Data简介

Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问技术,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。

Spring Data 包含多个子项目:

  • Spring Data Commons
  • Spring Data JPA
  • Spring Data KeyValue
  • Spring Data LDAP
  • Spring Data MongoDB
  • Spring Data Gemfire
  • Spring Data REST
  • Spring Data Redis
  • Spring Data for Apache Cassandra
  • Spring Data for Apache Solr
  • Spring Data Couchbase (community module)
  • Spring Data Elasticsearch (community module)
  • Spring Data Neo4j (community module)

1、Spring Data特点

Spring Data为我们提供使用统一的API来对数据访问层进行操作;这主要是Spring Data Commons项目来实现的。Spring Data Commons让我们在使用关系型或者非关系型数据访问技术时都基于Spring提供的统一标准,标准包含了CRUD(创建、获取、更新、删除)、查询、排序和分页的相关操作。

2、统一的Repository接口

Repository<T, ID extends Serializable>:统一接口

RevisionRepository<T, ID extends Serializable, N extends Number & Comparable<N>>:基于乐观锁机制

CrudRepository<T, ID extends Serializable>:基本CRUD操作

PagingAndSortingRepository<T, ID extends Serializable>:基本CRUD及分页

3、提供数据访问模板类 xxxTemplate;

如:MongoTemplate、RedisTemplate等。

4、JPA与Spring Data

  1. JpaRepository基本功能:编写接口继承JpaRepository既有crud及分页等基本功能
  2. 定义符合规范的方法命名:在接口中只需要声明符合规范的方法,即拥有对应的功能
  3. @Query自定义查询,定制查询SQL
  4. Specifications查询(Spring Data JPA支持JPA2.0的Criteria查询)

2.整合SpringData JPA

新建Spring Boot项目,勾选Spring Web、JDBC API、Spring JPA、MySQL Driver。创建jpa数据库。

1.编写实体列和数据表进行映射,配置好映射关系

package com.atguigu.springboot.entity;

import javax.persistence.*;

@Entity
@Table(name = "user")
public class User {
    @Id // 标注这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主键
    private int id;
    @Column(name = "name", length = 50)
    private String name;
    @Column // 不带name属性,默认就是属性名
    private String email;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

2.编写Dao接口操作实体类对应的数据表

package com.atguigu.springboot.repository;

import com.atguigu.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

// 继承JpaRepository完成对数据库的操作
public interface UserRepository extends JpaRepository<User, Integer> {
}

记得带上JpaRepository后面的泛型,否则启动会报错。 

3.在yml里做基本配置

spring:
  datasource:
    url: jdbc:mysql://192.168.0.123:3306/jpa?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      # 更新或创建数据表结构
      ddl-auto: update
    # 控制台显示SQL
    show-sql: true

4.写一个Controller做测试

package com.atguigu.springboot.controller;

import com.atguigu.springboot.entity.User;
import com.atguigu.springboot.repository.UserRepository;
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;

@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") int id) {
        User user = userRepository.findById(id).get();
        return user;
    }

    @GetMapping("/user")
    public User insertUser(User user) {
        User saveUser = userRepository.save(user);
        return saveUser;
    }
}

发送http://localhost:8080/user?name=wang&email=123@gmail.com请求插入一条数据,发送http://localhost:8080/user/1请求获取到数据。同时,我们可以在控制台看到打印的SQL。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值