• SpringBoot整合ORM开发框架MyBatis和JPA


    1、在使用Spring整合ORM组件的过程中,为了达到简化的目的,往往会进行大量的配置。利用SpringBoot可以进一步实现配置的简化。SpringBoot整合MyBatis开发框架,MyBatis是一款常用并且配置极为简单的ORM开发框架。其与Spring结合后,可以利用Spring的特征实现DAO接口的自动配置。在SpringBoot中,又对MyBatis框架的整合进行了进一步简化。

    修改pom.xml配置文件,在项目中引入mybatis-spring-boot- starter依赖支持库,切记也需要数据库链接池的支持的哦。

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
     5     https://maven.apache.org/xsd/maven-4.0.0.xsd">
     6 
     7     <modelVersion>4.0.0</modelVersion>
     8     <parent>
     9         <!-- spring-boot-starter-parent就是官方给出的快速构建SpringBoot项目的公共父pom.xml配置文件支持。 -->
    10         <groupId>org.springframework.boot</groupId>
    11         <artifactId>spring-boot-starter-parent</artifactId>
    12         <version>2.3.4.RELEASE</version>
    13         <relativePath /> <!-- lookup parent from repository -->
    14     </parent>
    15 
    16     <groupId>com.bie</groupId>
    17     <artifactId>springboot-01</artifactId>
    18     <version>0.0.1-SNAPSHOT</version>
    19     <name>springboot-01</name>
    20     <description>Demo project for Spring Boot</description>
    21 
    22     <properties>
    23         <java.version>1.8</java.version>
    24         <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    25     </properties>
    26 
    27     <dependencies>
    28         <dependency>
    29             <groupId>org.springframework.boot</groupId>
    30             <artifactId>spring-boot-starter-web</artifactId>
    31         </dependency>
    32 
    33         <dependency>
    34             <groupId>org.springframework.boot</groupId>
    35             <artifactId>spring-boot-starter-test</artifactId>
    36             <scope>test</scope>
    37             <exclusions>
    38                 <exclusion>
    39                     <groupId>org.junit.vintage</groupId>
    40                     <artifactId>junit-vintage-engine</artifactId>
    41                 </exclusion>
    42             </exclusions>
    43         </dependency>
    44         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    45         <dependency>
    46             <groupId>mysql</groupId>
    47             <artifactId>mysql-connector-java</artifactId>
    48             <!-- <version>5.1.12</version> -->
    49         </dependency>
    50         <dependency>
    51             <groupId>org.springframework.boot</groupId>
    52             <artifactId>spring-boot-configuration-processor</artifactId>
    53             <optional>true</optional>
    54         </dependency>
    55 
    56         <!-- 引入 Druid 数据源依赖:https://mvnrepository.com/artifact/com.alibaba/druid -->
    57         <dependency>
    58             <groupId>com.alibaba</groupId>
    59             <artifactId>druid</artifactId>
    60             <version>1.1.9</version>
    61         </dependency>
    62         <!-- 导入MyBatis的ORM开发包。 -->
    63         <dependency>
    64             <groupId>org.mybatis.spring.boot</groupId>
    65             <artifactId>mybatis-spring-boot-starter</artifactId>
    66             <version>1.3.1</version>
    67         </dependency>
    68         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    69         <dependency>
    70             <groupId>org.mybatis</groupId>
    71             <artifactId>mybatis</artifactId>
    72             <version>3.4.6</version>
    73         </dependency>
    74         <!-- mybatis的启动器 -->
    75         <dependency>
    76             <groupId>org.mybatis.spring.boot</groupId>
    77             <artifactId>mybatis-spring-boot-starter</artifactId>
    78             <version>2.1.1</version>
    79         </dependency>
    80         <dependency>
    81             <groupId>org.springframework.boot</groupId>
    82             <artifactId>spring-boot-starter-jdbc</artifactId>
    83         </dependency>
    84     </dependencies>
    85 
    86     <build>
    87         <plugins>
    88             <plugin>
    89                 <groupId>org.springframework.boot</groupId>
    90                 <artifactId>spring-boot-maven-plugin</artifactId>
    91             </plugin>
    92         </plugins>
    93     </build>
    94 
    95 </project>

    数据表结构,如下所示:

    注意:如果数据表字段两个英文单词之间是下划线连接的,但是你的实体类是驼峰命名法,此时就需要进行配置,数据库字段是你下划线分隔,但是bean中的字段是驼峰命名的,如user_name和userName,导致无法匹配。如果是通过xml文件来配置的话,只需要开启驼峰命名转换,setting name="mapUnderscoreToCamelCase" value="true"/>,在/src/main/resources/mybatis/mybatis.cfg.xml里面配置即可。

     1 /*
     2  Navicat Premium Data Transfer
     3 
     4  Source Server         : localhost
     5  Source Server Type    : MySQL
     6  Source Server Version : 50724
     7  Source Host           : localhost:3306
     8  Source Schema         : biehl
     9 
    10  Target Server Type    : MySQL
    11  Target Server Version : 50724
    12  File Encoding         : 65001
    13 
    14  Date: 15/11/2020 13:34:52
    15 */
    16 
    17 SET NAMES utf8mb4;
    18 SET FOREIGN_KEY_CHECKS = 0;
    19 
    20 -- ----------------------------
    21 -- Table structure for user_info
    22 -- ----------------------------
    23 DROP TABLE IF EXISTS `user_info`;
    24 CREATE TABLE `user_info`  (
    25   `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户编号',
    26   `user_account` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户账号',
    27   `user_pw` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户密码',
    28   `user_number` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户手机号',
    29   `user_name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户姓名',
    30   `user_age` int(11) DEFAULT NULL COMMENT '用户年龄',
    31   `user_sex` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户性别',
    32   `user_mark` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户标志',
    33   `create_time` datetime(0) DEFAULT CURRENT_TIMESTAMP COMMENT '用户创建时间',
    34   `is_sync` int(3) DEFAULT 0 COMMENT '用户标识',
    35   `is_money` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '是否缴纳押金',
    36   PRIMARY KEY (`user_id`) USING BTREE,
    37   INDEX `user_id`(`user_id`) USING BTREE
    38 ) ENGINE = InnoDB AUTO_INCREMENT = 42 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic;
    39 
    40 SET FOREIGN_KEY_CHECKS = 1;

    创建一个po实体类,方便数据传输,如下所示:

     1 package com.bie.po;
     2 
     3 public class UserInfo {
     4 
     5     private Integer userId;// 用户编号
     6     private String userAccount;// 用户账号
     7     private String userPw;// 用户密码
     8     private String userNumber;// 用户学号
     9     private String userName;// 用户姓名
    10     private Integer userAge;// 用户年龄
    11     private String userSex;// 用户性别
    12     private String userMark;// 用户标识,可以使用一张表,完成管理员和用户
    13 
    14     private String isMoney;
    15 
    16     public Integer getUserId() {
    17         return userId;
    18     }
    19 
    20     public void setUserId(Integer userId) {
    21         this.userId = userId;
    22     }
    23 
    24     public String getUserAccount() {
    25         return userAccount;
    26     }
    27 
    28     public void setUserAccount(String userAccount) {
    29         this.userAccount = userAccount;
    30     }
    31 
    32     public String getUserPw() {
    33         return userPw;
    34     }
    35 
    36     public void setUserPw(String userPw) {
    37         this.userPw = userPw;
    38     }
    39 
    40     public String getUserNumber() {
    41         return userNumber;
    42     }
    43 
    44     public void setUserNumber(String userNumber) {
    45         this.userNumber = userNumber;
    46     }
    47 
    48     public String getUserName() {
    49         return userName;
    50     }
    51 
    52     public void setUserName(String userName) {
    53         this.userName = userName;
    54     }
    55 
    56     public Integer getUserAge() {
    57         return userAge;
    58     }
    59 
    60     public void setUserAge(Integer userAge) {
    61         this.userAge = userAge;
    62     }
    63 
    64     public String getUserSex() {
    65         return userSex;
    66     }
    67 
    68     public void setUserSex(String userSex) {
    69         this.userSex = userSex;
    70     }
    71 
    72     public String getUserMark() {
    73         return userMark;
    74     }
    75 
    76     public void setUserMark(String userMark) {
    77         this.userMark = userMark;
    78     }
    79 
    80     public String getIsMoney() {
    81         return isMoney;
    82     }
    83 
    84     public void setIsMoney(String isMoney) {
    85         this.isMoney = isMoney;
    86     }
    87 
    88     @Override
    89     public String toString() {
    90         return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw + ", userNumber="
    91                 + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex
    92                 + ", userMark=" + userMark + ", isMoney=" + isMoney + "]";
    93     }
    94 
    95 }

    在src/main/resources目录中创建mybatis/mybatis.cfg.xml配置文件。如果要开启驼峰命名转换,在这里开启即可,如下所示:

    如果在application.properties中开启转换的话,使用mybatis.configuration.map-underscore-to-camel-case=true配置即可。

     1 <?xml version="1.0" encoding="UTF-8" ?> 
     2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
     3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
     4 <!-- 进行Mybatis的相应环境的属性定义 -->
     5 <configuration>
     6 
     7     <settings>
     8         <!-- 通过xml文件来配置的话,只需要开启驼峰命名转换 -->
     9         <setting name="mapUnderscoreToCamelCase" value="true" />
    10     </settings>
    11 
    12 </configuration>

    或者搞个配置类,如果数据库表字段Column无法自动映射到相对应的实体类属性上,我们可以在config包下新建一个自动配置类MybatisConfig,开始驼峰命名规则。

    MyBatis配置文件开启驼峰命名映射,可参考:https://blog.csdn.net/liu_sisi/article/details/88360155

     1 package com.bie.config;
     2  
     3 import org.apache.ibatis.session.Configuration;
     4 import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
     5 import org.springframework.context.annotation.Bean;
     6  
     7 
     8 @Configuration
     9 public class MybatisConfig {
    10  
    11     //注册到容器中
    12     @Bean
    13     public ConfigurationCustomizer configurationCustomizer(){
    14         return new ConfigurationCustomizer(){
    15             @Override
    16             public void customize(Configuration configuration) {
    17                 //开启驼峰命名规则,是否启用下划线与驼峰式命名规则的映射
    18                 configuration.setMapUnderscoreToCamelCase(true);
    19  
    20             }
    21         };
    22     }
    23 }

    修改application.yml配置文件,追加MyBatis配置,如下所示:

     1 # 配置当前要使用的数据源的操作类型
     2 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
     3 # 配置Mysql的驱动程序类
     4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
     5 # 数据库连接地址
     6 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/biehl?characterEncoding=UTF-8&serverTimezone=UTC
     7 # 数据库用户名称
     8 spring.datasource.username=root
     9 # 数据库密码
    10 spring.datasource.password=123456
    11 # 进行数据库链接池的配置,数据库最小维持连接数
    12 spring.datasource.dbcp2.min-idle=1
    13 # 数据库初始化提供的连接数
    14 spring.datasource.dbcp2.initial-size=1
    15 # 数据库最大维持连接数
    16 spring.datasource.dbcp2.max-total=100
    17 # 等待连接获取的最大超时时间
    18 spring.datasource.dbcp2.max-wait-millis=3000
    19 
    20 
    21 # 后台打印sql语句
    22 # mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    23 # 指定sql映射文件位置,mapper下的所有.xml文件都是映射文件
    24 # mybatis.mapper-locations=classpath:mapper/*Mapper.xml
    25 # Mybatis配置文件所在的路径
    26 mybatis.config-location=classpath:mybatis/mybatis.cfg.xml
    27 # 定义所有操作类的别名所在包
    28 mybatis.type-aliases-package=com.bie.po

    搞几个Dao层、Service层、Controller层的接口或者类,如下所示:

    注意:如果不想每次都在mapper接口上添加@Mapper注解,可以在主启动类上通过添加@MapperScan注解来批量扫描指定包下的所有mapper接口。

     1 package com.bie.dao;
     2 
     3 import java.util.List;
     4 
     5 import org.apache.ibatis.annotations.Mapper;
     6 import org.apache.ibatis.annotations.Select;
     7 
     8 import com.bie.po.UserInfo;
     9 
    10 @Mapper // 需要引入Mybatis的依赖包
    11 public interface UserInfoDao {
    12 
    13     /**
    14      * 查询全部用户信息
    15      * 
    16      * @return
    17      */
    18     @Select(value = " select * from user_info ")
    19     public List<UserInfo> findAll(); // 查询全部用户信息
    20 
    21 }

    Service层的接口和实现类代码,如下所示:

     1 package com.bie.service;
     2 
     3 import java.util.List;
     4 
     5 import com.bie.po.UserInfo;
     6 
     7 public interface UserInfoService {
     8     
     9     public List<UserInfo> findAll();
    10 }
     1 package com.bie.service.impl;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Service;
     7 
     8 import com.bie.dao.UserInfoDao;
     9 import com.bie.po.UserInfo;
    10 import com.bie.service.UserInfoService;
    11 
    12 @Service
    13 public class UserInfoServiceImpl implements UserInfoService {
    14 
    15     @Autowired
    16     private UserInfoDao userInfoDao;
    17 
    18     @Override
    19     public List<UserInfo> findAll() {
    20         return this.userInfoDao.findAll();
    21     }
    22 
    23 }

    控制层的代码,如下所示:

     1 package com.bie.controller;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Controller;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.ResponseBody;
     9 
    10 import com.bie.po.UserInfo;
    11 import com.bie.service.UserInfoService;
    12 
    13 @Controller
    14 public class UserInfoController {
    15 
    16     @Autowired
    17     private UserInfoService userInfoService;
    18 
    19     @RequestMapping(value = "findAll")
    20     @ResponseBody
    21     public List<UserInfo> findAll() {
    22         List<UserInfo> findAll = this.userInfoService.findAll();
    23         return findAll;
    24     }
    25 
    26 }

    项目启动类,如下所示:

     1 package com.bie;
     2 
     3 import org.mybatis.spring.annotation.MapperScan;
     4 import org.springframework.boot.SpringApplication;
     5 import org.springframework.boot.autoconfigure.SpringBootApplication;
     6 
     7 @SpringBootApplication
     8 @MapperScan(value = "com.bie.dao")
     9 public class Springboot01Application {
    10 
    11     public static void main(String[] args) {
    12         SpringApplication.run(Springboot01Application.class, args);
    13     }
    14 
    15 }

    通过Postman测试一下,自己写的接口,看看好使不,如下所示:

    项目结构,如下所示:

    2、JPA是官方推出的Java持久层操作标准(现主要使用Hibernate实现),使用SpringData技术和JpaRepository接口技术,也可以达到简化数据层的目的。要在SpringBoot中使用SpringDataJPA,需要spring-boot-starter-data-jpa依赖库的支持。

    修改pom.xml配置文件,引入相关依赖包,如下所示:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
     5     https://maven.apache.org/xsd/maven-4.0.0.xsd">
     6     <modelVersion>4.0.0</modelVersion>
     7     <parent>
     8         <groupId>org.springframework.boot</groupId>
     9         <artifactId>spring-boot-starter-parent</artifactId>
    10         <version>2.3.5.RELEASE</version>
    11         <relativePath /> <!-- lookup parent from repository -->
    12     </parent>
    13     <groupId>com.example</groupId>
    14     <artifactId>demo</artifactId>
    15     <version>0.0.1-SNAPSHOT</version>
    16     <name>demo</name>
    17     <description>Demo project for Spring Boot</description>
    18 
    19     <properties>
    20         <java.version>1.8</java.version>
    21         <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    22     </properties>
    23 
    24     <dependencies>
    25         <dependency>
    26             <groupId>org.springframework.boot</groupId>
    27             <artifactId>spring-boot-starter-web</artifactId>
    28         </dependency>
    29 
    30         <dependency>
    31             <groupId>org.springframework.boot</groupId>
    32             <artifactId>spring-boot-starter-test</artifactId>
    33             <scope>test</scope>
    34             <exclusions>
    35                 <exclusion>
    36                     <groupId>org.junit.vintage</groupId>
    37                     <artifactId>junit-vintage-engine</artifactId>
    38                 </exclusion>
    39             </exclusions>
    40         </dependency>
    41 
    42         <!-- mysql驱动包 -->
    43         <dependency>
    44             <groupId>mysql</groupId>
    45             <artifactId>mysql-connector-java</artifactId>
    46         </dependency>
    47 
    48         <!-- druid连接池 -->
    49         <dependency>
    50             <groupId>com.alibaba</groupId>
    51             <artifactId>druid</artifactId>
    52             <version>1.1.10</version>
    53         </dependency>
    54 
    55         <dependency>
    56             <groupId>org.springframework.boot</groupId>
    57             <artifactId>spring-boot-starter-data-jpa</artifactId>
    58         </dependency>
    59         <dependency>
    60             <groupId>org.springframework.boot</groupId>
    61             <artifactId>spring-boot-starter-cache</artifactId>
    62         </dependency>
    63         <dependency>
    64             <groupId>org.hibernate</groupId>
    65             <artifactId>hibernate-ehcache</artifactId>
    66         </dependency>
    67     </dependencies>
    68 
    69     <build>
    70         <plugins>
    71             <plugin>
    72                 <groupId>org.springframework.boot</groupId>
    73                 <artifactId>spring-boot-maven-plugin</artifactId>
    74             </plugin>
    75         </plugins>
    76         <resources>
    77             <resource>
    78                 <directory>src/main/resources</directory>
    79                 <includes>
    80                     <include>**/*.properties</include>
    81                     <include>**/*.yml</include>
    82                     <include>**/*.xml</include>
    83                     <include>**/*.p12</include>
    84                     <include>**/*.html</include>
    85                     <include>**/*.jpg</include>
    86                     <include>**/*.png</include>
    87                 </includes>
    88             </resource>
    89         </resources>
    90     </build>
    91 
    92 </project>

    创建UserInfo实体类,如下所示:

      1 package com.demo.po;
      2 
      3 import javax.persistence.Cacheable;
      4 import javax.persistence.Column;
      5 import javax.persistence.Entity;
      6 import javax.persistence.GeneratedValue;
      7 import javax.persistence.GenerationType;
      8 import javax.persistence.Id;
      9 
     10 @Cacheable()
     11 @Entity(name = "user_info")
     12 public class UserInfo {
     13 
     14     @Id()
     15     @Column(name = "user_id")
     16     @GeneratedValue(strategy = GenerationType.IDENTITY) // 根据名称引用配置的主键生成器
     17     private Integer userId;// 用户编号
     18 
     19     @Column(name = "user_account")
     20     private String userAccount;// 用户账号
     21 
     22     @Column(name = "user_pw")
     23     private String userPw;// 用户密码
     24 
     25     @Column(name = "user_number")
     26     private String userNumber;// 用户学号
     27 
     28     @Column(name = "user_name")
     29     private String userName;// 用户姓名
     30 
     31     @Column(name = "user_age")
     32     private Integer userAge;// 用户年龄
     33 
     34     @Column(name = "user_sex")
     35     private String userSex;// 用户性别
     36 
     37     @Column(name = "user_mark")
     38     private String userMark;// 用户标识,可以使用一张表,完成管理员和用户
     39 
     40     @Column(name = "is_money")
     41     private String isMoney;
     42 
     43     public Integer getUserId() {
     44         return userId;
     45     }
     46 
     47     public void setUserId(Integer userId) {
     48         this.userId = userId;
     49     }
     50 
     51     public String getUserAccount() {
     52         return userAccount;
     53     }
     54 
     55     public void setUserAccount(String userAccount) {
     56         this.userAccount = userAccount;
     57     }
     58 
     59     public String getUserPw() {
     60         return userPw;
     61     }
     62 
     63     public void setUserPw(String userPw) {
     64         this.userPw = userPw;
     65     }
     66 
     67     public String getUserNumber() {
     68         return userNumber;
     69     }
     70 
     71     public void setUserNumber(String userNumber) {
     72         this.userNumber = userNumber;
     73     }
     74 
     75     public String getUserName() {
     76         return userName;
     77     }
     78 
     79     public void setUserName(String userName) {
     80         this.userName = userName;
     81     }
     82 
     83     public Integer getUserAge() {
     84         return userAge;
     85     }
     86 
     87     public void setUserAge(Integer userAge) {
     88         this.userAge = userAge;
     89     }
     90 
     91     public String getUserSex() {
     92         return userSex;
     93     }
     94 
     95     public void setUserSex(String userSex) {
     96         this.userSex = userSex;
     97     }
     98 
     99     public String getUserMark() {
    100         return userMark;
    101     }
    102 
    103     public void setUserMark(String userMark) {
    104         this.userMark = userMark;
    105     }
    106 
    107     public String getIsMoney() {
    108         return isMoney;
    109     }
    110 
    111     public void setIsMoney(String isMoney) {
    112         this.isMoney = isMoney;
    113     }
    114 
    115     @Override
    116     public String toString() {
    117         return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw + ", userNumber="
    118                 + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex
    119                 + ", userMark=" + userMark + ", isMoney=" + isMoney + "]";
    120     }
    121 
    122 }

    创建UserDao,然后继承JpaRepository<UserInfo, Integer>,此时就可以使用写好的方法了,不用自己再额外写接口和实现,如下所示:

     1 package com.demo.dao;
     2 
     3 import org.springframework.data.jpa.repository.JpaRepository;
     4 
     5 import com.demo.po.UserInfo;
     6 
     7 /**
     8  * 
     9  * @author 继承JpaRepository包含全部的基础CURD操作
    10  *
    11  */
    12 public interface UserDao extends JpaRepository<UserInfo, Integer> {
    13 
    14 }

    然后定义Service接口和Service接口实现,如下所示:

     1 package com.demo.service;
     2 
     3 import java.util.List;
     4 
     5 import com.demo.po.UserInfo;
     6 
     7 public interface UserService {
     8 
     9     public List<UserInfo> findAll();
    10 }
     1 package com.demo.service.impl;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Service;
     7 
     8 import com.demo.dao.UserDao;
     9 import com.demo.po.UserInfo;
    10 import com.demo.service.UserService;
    11 
    12 @Service
    13 public class UserServiceImpl implements UserService {
    14 
    15     @Autowired
    16     private UserDao userDao;
    17 
    18     @Override
    19     public List<UserInfo> findAll() {
    20 
    21         return userDao.findAll();
    22     }
    23 
    24 }

    然后搞一个Controller,作为接口访问的入口,如下所示:

     1 package com.demo.controller;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Controller;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.ResponseBody;
     9 
    10 import com.demo.po.UserInfo;
    11 import com.demo.service.UserService;
    12 
    13 @Controller
    14 public class SpringBootController {
    15 
    16     @Autowired
    17     private UserService userService;
    18 
    19     @RequestMapping(value = "/findAll")
    20     @ResponseBody
    21     public List<UserInfo> findAll() {
    22         List<UserInfo> findAll = userService.findAll();
    23         return findAll;
    24     }
    25 
    26 }

    修改程序启动主类,追加Repository扫描配置。如果使用JpaRepository实现了DAO接口的自动实现。需要注意的是,如果想启用Repository配置,则需要在程序启动主类时使用@EnableJpaRepositories注解配置扫描包,而后才可以正常使用。

     1 package com.demo;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
     6 
     7 @SpringBootApplication // 启动Springboot程序,而后自带子包扫描
     8 @EnableJpaRepositories(basePackages = "com.demo.dao")
     9 public class DemoApplication {
    10 
    11     public static void main(String[] args) {
    12         // 启动Springboot程序
    13         SpringApplication.run(DemoApplication.class, args);
    14     }
    15 
    16 }

    修改application.properties,使用Druid作为数据源连接池,如下所示:

     1 # mysql的数据库驱动
     2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
     3 # mysql的链接
     4 spring.datasource.url=jdbc:mysql://localhost:3306/biehl
     5 # mysql的账号
     6 spring.datasource.username=root
     7 # mysql的密码
     8 spring.datasource.password=123456
     9 
    10 # druid连接池的配置
    11 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    12 
    13 # Spring Data JPA,此配置可以在实体类中使用注解来创建数据表,开启正向工程
    14 spring.jpa.hibernate.ddl-auto=update
    15 # 在控制台打印sql语句
    16 spring.jpa.show-sql=true

    使用postman进行接口调用,如下所示:

  • 相关阅读:
    Shell入门
    Linux基本的指令操作
    python网络爬虫入门范例
    Android中scrollview的scrollto方法不起作用的解决办法
    (转)Android利用canvas画各种图形(点、直线、弧、圆、椭圆、文字、矩形、多边形、曲线、圆角矩形)
    unable to load class org.codehaus.groovy.runtime.typehandling.shorttypehandling解决方法
    JavaScript运行原理
    AsyncTask的doInBackground不工作原因分析
    Android中的多线程与异步任务
    使用webview加载网页时session同步
  • 原文地址:https://www.cnblogs.com/biehongli/p/13976518.html
Copyright © 2020-2023  润新知