springboot + jpa(hibernate) + MySQL

文章目录

0、先导知识

(1)后端项目代码分三层,controller层是对外提供的接口层,service层是逻辑实现层,mapper是操作数据库的仓储层。domain层的实体类在以上三层中都会用到
springboot + jpa(hibernate) + MySQL
(2)jpa简答介绍
JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

使用jpa的好处就是不用写sql语句,但是一般的企业项目中都不会用jpa,因为jpa的缺点就是不够灵活,不能够完全自定义sql语句,只能使用jpa提供的方法,实际企业项目中大多都用mybatis。

举例子感受一下使用 jpa 和 使用 mybatis 的区别

1)使用 jpa

User findByAccount(String account);

jpa中的查询语句都是find开头,在By后面添加查询条件,这里的Account是数据库表中的字段名称
springboot + jpa(hibernate) + MySQL
可以多条件查询

User findByAccountAndPassword(String account,String password);

模糊查询

List<User> findAllByAccountLikeOrUsernameLike(String account, String username);

2)使用 mybatis

    <select id="findByAccount" resultType="com.example.springbootmybatismysql.domain.User">
		select * from springboot_demo.user
		where account=#{account}
	</select>

多条件查询

    <select id="findByAccountAndPassword" resultType="com.example.springbootmybatismysql.domain.User">
		select * from springboot_demo.user
		where account=#{account} and password=#{password}
	</select>

模糊查询

    <select id="findAllByAccountLikeOrUsernameLike" resultMap="userResultMap">
		select * from springboot_demo.user
		where account like concat('%',#{keywords},'%') or username like concat('%',#{keywords},'%')
	</select>

1、新建项目

这里有介绍,此处不赘述:springboot简单应用

2、新建基本目录

先创建基本目录:controller(控制器层)、service(逻辑层)、mapper(仓储层)、domain(领域层),result文件下是一些工具类
springboot + jpa(hibernate) + MySQL

3、添加依赖

jpa的依赖

        <!-- jpa 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

mysql的依赖,mysql有5.0的版本和8.0的版本,这里我用的是5.0的版本

<!--        &lt;!&ndash;  mysql 8 &ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>mysql</groupId>-->
<!--            <artifactId>mysql-connector-java</artifactId>-->
<!--            <version>8.0.15</version>-->
<!--        </dependency>-->

        <!--  mysql 5  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

完整的pom文件,除了jpa的依赖和mysql的依赖,其他的依赖都是新建项目时自动生成的

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>springboot-jpa-mysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-jpa-mysql</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- jpa 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

<!--        &lt;!&ndash;  mysql 8 &ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>mysql</groupId>-->
<!--            <artifactId>mysql-connector-java</artifactId>-->
<!--            <version>8.0.15</version>-->
<!--        </dependency>-->

        <!--  mysql 5  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.springbootjpamysql.SpringbootJpaMysqlApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

4、添加配置文件

在application.properties文件中添加配置信息

# 应用名称
spring.application.name=springboot-jpa-mysql
# 应用服务 WEB 访问端口
server.port=8080

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot_demo?serverTimezone=UTC&useSSL=false&tinyInt1isBit=false&zeroDateTimeBehavior=round
spring.datasource.username=root
spring.datasource.password=root
#MySQL 8
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#MySQL 5
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto = none

mysql 8.0 和mysql 5.0的驱动器是不一样的,我用的是5.0的。
数据库连接账号和密码我这里都是root

5、新建数据库

先新建数据库 springboot_demo,再执行下面的sql语句新建表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  `username` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of User
-- ----------------------------
INSERT INTO `user` VALUES (1, '1001', 'test1', '123456');
INSERT INTO `user` VALUES (2, '1002', 'test2', '123456');
INSERT INTO `user` VALUES (3, '1003', 'test3', '123456');
INSERT INTO `user` VALUES (4, '1004', 'test4', '123456');

6、新建类

(1)在domain目录下新建实体类 User

package com.example.springbootjpamysql.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;

@Entity
@Table(name = "user")
@JsonIgnoreProperties({"handler","hibernateLazyInitializer"})
public class User {
    //主键定义,只能有一个,选择对应的列名
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    int id;
    String account;
    String username;
    String password;

    public int getId() {
        return id;
    }

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

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    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;
    }
}

(2)在mapper目录下新建接口 UserMapper

package com.example.springbootjpamysql.mapper;

import com.example.springbootjpamysql.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserMapper extends JpaRepository<User, Integer> {
    User findById(int id);
    User findByAccount(String account);
    User findByAccountAndPassword(String account,String password);
    List<User> findAllByUsernameLike(String username);
    List<User> findAllByAccountLikeOrUsernameLike(String account, String username);
}

(3)在result目录下新建类 Search

package com.example.springbootjpamysql.result;

public class Search {
    String keywords;

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }
}

(4)在service目录下新建接口 UserService

package com.example.springbootjpamysql.service;

import com.example.springbootjpamysql.domain.User;

import java.util.List;

public interface UserService {
    List<User> getAllUser();
    User findById(int id);
    User findByAccount(String account);
    User findByAccountAndPassword(String account, String password);
    List<User> findAllByUsernameLike(String keywords);
    List<User> findAllByAccountLikeOrUsernameLike(String keywords);
    void deleteById(int id);
    User add(User user);
    User update(User user);

}

(5)在service->impl 目录下新建类 UserServiceImpl

package com.example.springbootjpamysql.service.impl;

import com.example.springbootjpamysql.domain.User;
import com.example.springbootjpamysql.mapper.UserMapper;
import com.example.springbootjpamysql.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> getAllUser() {
        return userMapper.findAll();
    }

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public User findByAccount(String account) {
        return userMapper.findByAccount(account);
    }

    @Override
    public User findByAccountAndPassword(String account, String password) {
        return userMapper.findByAccountAndPassword(account,password);
    }

    @Override
    public List<User> findAllByUsernameLike(String keywords) {
        return userMapper.findAllByUsernameLike('%' + keywords + '%');
    }

    @Override
    public List<User> findAllByAccountLikeOrUsernameLike(String keywords) {
        return userMapper.findAllByAccountLikeOrUsernameLike('%' + keywords + '%','%' + keywords + '%');
    }

    @Override
    public void deleteById(int id) {
        userMapper.deleteById(id);
    }

    @Override
    public User add(User user) {
        return userMapper.save(user);
    }

    @Override
    public User update(User user) {
        return userMapper.save(user);
    }
}

(6)在controller目录下新建类 UserController

package com.example.springbootjpamysql.controller;

import com.example.springbootjpamysql.domain.User;
import com.example.springbootjpamysql.result.Search;
import com.example.springbootjpamysql.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/api/getAllUser")
    public List<User> getAllUser() throws Exception {
        return userService.getAllUser();
    }

    @PostMapping("/api/findById")
    public User findById(int id) throws Exception {
        return userService.findById(id);
    }

    @PostMapping("/api/findByAccount")
    public User findByAccount(@RequestBody Search s) throws Exception {
        return userService.findByAccount(s.getKeywords());
    }

    @PostMapping("/api/findByAccountAndPassword")
    public User findByAccountAndPassword(@RequestBody User user) throws Exception {
        return userService.findByAccountAndPassword(user.getAccount(),user.getPassword());
    }

    @PostMapping("/api/findAllByUsernameLike")
    public  List<User> findAllByUsernameLike(@RequestBody Search s) throws Exception {
        return userService.findAllByUsernameLike(s.getKeywords());
    }

    @PostMapping("/api/findAllByAccountLikeOrUsernameLike")
    public List<User> findAllByAccountLikeOrUsernameLike(@RequestBody Search s) throws Exception {
        return userService.findAllByAccountLikeOrUsernameLike(s.getKeywords());
    }

    @PostMapping("/api/addUser")
    public User addUser(@RequestBody User user) throws Exception {
        User user1 = userService.findByAccount(user.getAccount());
        if (user1 != null){
            return null;
        }else {
            userService.add(user);
            return user;
        }
    }

    @PostMapping("/api/updateUser")
    public User updateUser(@RequestBody User user) throws Exception {
        User user1 = userService.findByAccount(user.getAccount());
        if (user1 != null){
            userService.update(user);
            return user;
        }else {
            return null;
        }
    }

    @PostMapping("/api/deleteUser")
    public User deleteUser(@RequestBody User user) throws Exception {
        User user1 = userService.findByAccount(user.getAccount());
        if (user1 != null){
            userService.deleteById(user.getId());
            return user;
        }else {
            return null;
        }
    }
}

(7)创建完毕后的目录结构是这样的

springboot + jpa(hibernate) + MySQL

7、测试

启动项目,用postman测试

增删改
http://localhost:8080/api/addUser
http://localhost:8080/api/deleteUser
http://localhost:8080/api/updateUser

springboot + jpa(hibernate) + MySQL

获取所有user
http://localhost:8080/api/getAllUser

springboot + jpa(hibernate) + MySQL

模糊查询
findAllByAccountLikeOrUsernameLike
http://localhost:8080/api/findAllByAccountLikeOrUsernameLike

springboot + jpa(hibernate) + MySQL

8、源码

springboot-jpa-mysql

上一篇:java创建指定大小的文件,看看这篇文章吧!


下一篇:悲/乐观并发控制的区别