Java (1): Create a Spring Boot project and implement connection operations to the MySQL database

Create a Spring Boot project and implement the connection operation MySQL database

Prepare

MySQL

Insert image description here

Order

$ docker pull mysql
$ docker run --name local-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql

Maven

Related addresses

download link:

https://maven.apache.org/

maven configuration method address:

https://developer.aliyun.com/mvn/guide

Warehouse search address:

https://mvnrepository.com/

https://repo.maven.apache.org/

mavenlocal configurationconf/settings.xml

<!-- TAG··· -->

<!-- 指定下载依赖到本地的路径 -->
<localRepository>${user.home}/Documents/AAA-PLee/maven/repository</localRepository>

        <!-- TAG··· -->

        <!-- 配置为阿里云公共仓库 -->
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>

        <!-- TAG··· -->

Download ideaand configure the local environmentmaven

Insert image description here

MavenConstruct生命周期

  • MavenThe construction 生命周期includes 三个阶段: clean, buildandsite
    1. clean: Clean the project, delete previous compilation results and files generated by the build.
    2. build: Build the project, including compilation, testing, packaging and other operations.
    3. site: Generate project documents and reports, such as test reports, code coverage reports, etc.
  • Each stage contains some plug-ins and targets, which Mavenare executed in a predefined order. For example, in builda stage, Maventhe following goals are executed in sequence:
    1. validate: Verify that the project is correct.
    2. compile: Compile the project source code.
    3. test: Run the test cases of the project.
    4. package: Package the project into a jar or war file.
    5. verify: Verify whether the packaging result is correct.
    6. install: Install the packaging results to the local Maven repository.
    7. deploy: Deploy the packaging results to the remote Maven repository.

ideaDownload required plug-ins

Insert image description here

EasyCode

Used to quickly generate database-related project directories and codes

MyBatisPlus

Used to jump between javaandsql.xml

ideaCreate project

ConfigurationServer URL

Address: https://start.aliyun.com/

Insert image description here

Fill in project related information

Insert image description here

Insert image description here

Project creation successful (run and test)

Insert image description here

Insert image description here

Insert image description here

ideaTest whether the connection is normalMySQL

Insert image description here

Create database table

Insert image description here

Add MySQLconfiguration of connections within the project

Search for MySQLdependency packages used by the connection

Insert image description here

Write connection database configuration file

pom.xmlIntroduce in MySQL依赖包(don’t forget Load Maven Changes)


<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>

create and writeapplication.yml

path:user/src/main/resources/application.yml

server:
  port: 8000
spring:
  application:
    name: user-service
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/java_app
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

Use plug-ins EasyCodeto quickly create code related to operating databases

Insert image description here

Insert image description here

View the project directory structure after creation

Insert image description here

JavaApplications typically use the following components to organize their code

The relationship between these components is usually call Controller, Servicedefined Servicewithin implthe folder 业务实现类, 业务实现类call DAO, DAOoperation , representing the database table structureMapperSQL语句Entity实体类

Simply put, Controllerit is used to receive user requests, Serviceimplement business logic, DAOoperate the database, and Entityrepresent the database table structure.

/service/impl/xxx.javaImplement specific business logic in

Add statements /resources/mapper/xxx.xmlto manipulate data insql

  • Controller: Controller, used to receive user requests and call corresponding processing methods to process the requests, and then return the response results. Usually Spring MVCimplemented using a framework.
  • Service: Service layer, used to implement business logic and call to DAOperform data operations. Usually contains interface and implementation classes.
  • DAO: Data access object, used to operate the database. It is usually implemented using frameworks MyBatissuch Hibernateas .
  • Entity: Entity class, used to represent the table structure in the database. Usually contains class attributes and corresponding getter/settermethods.

Solve the problem of importing library errors in the project

Use https://mvnrepository.com/search solution

<!-- 解决完成后的pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Try to run (error: no corresponding version is introduced)

Insert image description here

<!-- <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
    <version>3.1.0</version>
</dependency> -->
<!-- 修改为 -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
</dependency>

Try running (missing @MapperScanannotations)

Insert image description here

Notice:尽量选择使用量大的依赖包


<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
// user/src/main/java/com/example/user/UserApplication.java

package com.example.user;

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

@SpringBootApplication
@MapperScan(basePackages = "com.example.user.dao")
public class UserApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(UserApplication.class, args);
    }
}
  • The @SpringBootApplication annotation is a combined annotation, which is used to mark
    the main class of a Spring Boot application. It includes three annotations: @Configuration, @EnableAutoConfigurationand@ComponentScan
    • @Configuration: Mark this class as the source of a bean definition in the Spring application context. That is, the beans defined in this class can be managed by the Spring container.
    • @EnableAutoConfiguration: Automatically configure the beans required by Spring Boot applications.
    • @ComponentScan: Scans other components in the application, such as controllers, services, and repositories.
  • @MapperScan is an annotation in the MyBatis framework. Its function is to scan the specified package path, find all interfaces marked with the @Mapper annotation, and create these interfaces into MyBatis Mapper interface implementation classes.
    • Instances of these Mapper implementation classes can be automatically injected wherever Mapper is needed, thereby conveniently accessing the database.

Try to run (the operation is successful, if it ends immediately after running, it may be that spring-boot-starter-webthe package has not been introduced)

Just try to import it


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

finallypom.xml


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Access interface

Request failed

Insert image description here

Insert image description here

Solve the error (tell MyBatiswhere to find SQLthe statement)

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

Rerun and request

Insert image description here

Complete source code

Directory Structure

Insert image description here

Introduce dependencies:user/pom.xml

<?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>user</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>user</name>
    <description>user</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.6.13</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.example.user.UserApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Service related configuration:user/src/main/resources/application.yml

server:
  port: 8000

spring:
  application:
    name: user-service
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/java_app
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

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

Entrance:user/src/main/java/com/example/user/UserApplication.java

package com.example.user;

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

@SpringBootApplication
@MapperScan(basePackages = "com.example.user.dao")
public class UserApplication {
    
    

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

}

(User) table control layer:user/src/main/java/com/example/user/controller/UserController.java

package com.example.user.controller;

import com.example.user.entity.User;
import com.example.user.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2023-06-12 14:13:44
 */
@RestController
@RequestMapping("user")
public class UserController {
    
    
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<User>> queryByPage(User user, PageRequest pageRequest) {
    
    
        return ResponseEntity.ok(this.userService.queryByPage(user, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<User> queryById(@PathVariable("id") String id) {
    
    
        return ResponseEntity.ok(this.userService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<User> add(User user) {
    
    
        return ResponseEntity.ok(this.userService.insert(user));
    }

    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<User> edit(User user) {
    
    
        return ResponseEntity.ok(this.userService.update(user));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(String id) {
    
    
        return ResponseEntity.ok(this.userService.deleteById(id));
    }

}

(User) table service interface:user/src/main/java/com/example/user/service/UserService.java

package com.example.user.service;

import com.example.user.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

/**
 * (User)表服务接口
 *
 * @author makejava
 * @since 2023-06-12 14:13:49
 */
public interface UserService {
    
    

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    User queryById(String id);

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    Page<User> queryByPage(User user, PageRequest pageRequest);

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    User insert(User user);

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    User update(User user);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    boolean deleteById(String id);

}

(User) table service implementation class:user/src/main/java/com/example/user/service/impl/UserServiceImpl.java

package com.example.user.service.impl;

import com.example.user.entity.User;
import com.example.user.dao.UserDao;
import com.example.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-06-12 14:13:50
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    
    
    @Resource
    private UserDao userDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(String id) {
    
    
        return this.userDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<User> queryByPage(User user, PageRequest pageRequest) {
    
    
        long total = this.userDao.count(user);
        return new PageImpl<>(this.userDao.queryAllByLimit(user, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
    
    
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
    
    
        this.userDao.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
    
    
        return this.userDao.deleteById(id) > 0;
    }
}

(User) table database access layer:user/src/main/java/com/example/user/dao/UserDao.java

package com.example.user.dao;

import com.example.user.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;

import java.util.List;

/**
 * (User)表数据库访问层
 *
 * @author makejava
 * @since 2023-06-12 14:13:45
 */
public interface UserDao {
    
    

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    User queryById(String id);

    /**
     * 查询指定行数据
     *
     * @param user 查询条件
     * @param pageable         分页对象
     * @return 对象列表
     */
    List<User> queryAllByLimit(User user, @Param("pageable") Pageable pageable);

    /**
     * 统计总行数
     *
     * @param user 查询条件
     * @return 总行数
     */
    long count(User user);

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 影响行数
     */
    int insert(User user);

    /**
     * 批量新增数据(MyBatis原生foreach方法)
     *
     * @param entities List<User> 实例对象列表
     * @return 影响行数
     */
    int insertBatch(@Param("entities") List<User> entities);

    /**
     * 批量新增或按主键更新数据(MyBatis原生foreach方法)
     *
     * @param entities List<User> 实例对象列表
     * @return 影响行数
     * @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参
     */
    int insertOrUpdateBatch(@Param("entities") List<User> entities);

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 影响行数
     */
    int update(User user);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteById(String id);

}

(User) entity class:user/src/main/java/com/example/user/entity/User.java

package com.example.user.entity;

import java.io.Serializable;

/**
 * (User)实体类
 *
 * @author makejava
 * @since 2023-06-12 14:13:46
 */
public class User implements Serializable {
    
    
    private static final long serialVersionUID = 264722085318530649L;

    private String id;

    private String name;

    private Integer age;

    private String sex;

    private String phone;


    public String getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

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

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

    public String getSex() {
    
    
        return sex;
    }

    public void setSex(String sex) {
    
    
        this.sex = sex;
    }

    public String getPhone() {
    
    
        return phone;
    }

    public void setPhone(String phone) {
    
    
        this.phone = phone;
    }

}

SQL:user/src/main/resources/mapper/UserDao.xml

<?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.example.user.dao.UserDao">

    <resultMap type="com.example.user.entity.User" id="UserMap">
        <result property="id" column="id" jdbcType="VARCHAR"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="sex" column="sex" jdbcType="VARCHAR"/>
        <result property="phone" column="phone" jdbcType="VARCHAR"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" resultMap="UserMap">
        select
        id, name, age, sex, phone
        from user
        where id = #{id}
    </select>

    <!--查询指定行数据-->
    <select id="queryAllByLimit" resultMap="UserMap">
        select
        id, name, age, sex, phone
        from user
        <where>
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="sex != null and sex != ''">
                and sex = #{sex}
            </if>
            <if test="phone != null and phone != ''">
                and phone = #{phone}
            </if>
        </where>
        limit #{pageable.offset}, #{pageable.pageSize}
    </select>

    <!--统计总行数-->
    <select id="count" resultType="java.lang.Long">
        select count(1)
        from user
        <where>
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="sex != null and sex != ''">
                and sex = #{sex}
            </if>
            <if test="phone != null and phone != ''">
                and phone = #{phone}
            </if>
        </where>
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into user(name, age, sex, phone)
        values (#{name}, #{age}, #{sex}, #{phone})
    </insert>

    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
        insert into user(name, age, sex, phone)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.name}, #{entity.age}, #{entity.sex}, #{entity.phone})
        </foreach>
    </insert>

    <insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
        insert into user(name, age, sex, phone)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.name}, #{entity.age}, #{entity.sex}, #{entity.phone})
        </foreach>
        on duplicate key update
        name = values(name),
        age = values(age),
        sex = values(sex),
        phone = values(phone)
    </insert>

    <!--通过主键修改数据-->
    <update id="update">
        update user
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
            <if test="sex != null and sex != ''">
                sex = #{sex},
            </if>
            <if test="phone != null and phone != ''">
                phone = #{phone},
            </if>
        </set>
        where id = #{id}
    </update>

    <!--通过主键删除-->
    <delete id="deleteById">
        delete from user where id = #{id}
    </delete>

</mapper>

Guess you like

Origin blog.csdn.net/weixin_43526371/article/details/131172144