Create a Spring Boot project and implement the connection operation MySQL database
-
- Prepare
- `idea` creates a project
- `idea` tests whether it can connect to `MySQL` normally
- Create database table
- Add configuration to connect to `MySQL` within the project
- Use the plug-in `EasyCode` to quickly create code related to operating databases
- Access interface
- Complete source code
-
- Directory Structure
- Introduce dependencies: `user/pom.xml`
- Service related configuration: `user/src/main/resources/application.yml`
- 入口:`user/src/main/java/com/example/user/UserApplication.java`
- (User) table control layer: `user/src/main/java/com/example/user/controller/UserController.java`
- (User) table service interface: `user/src/main/java/com/example/user/service/UserService.java`
- (User) table service implementation class: `user/src/main/java/com/example/user/service/impl/UserServiceImpl.java`
- (User) table database access layer: `user/src/main/java/com/example/user/dao/UserDao.java`
- (User)实体类:`user/src/main/java/com/example/user/entity/User.java`
- SQL:`user/src/main/resources/mapper/UserDao.xml`
Prepare
MySQL
Order
$ docker pull mysql
$ docker run --name local-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
Maven
Related addresses
download link:
maven configuration method address:
Warehouse search address:
maven
local 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 idea
and configure the local environmentmaven
Maven
Construct生命周期
Maven
The construction生命周期
includes三个阶段
:clean
,build
andsite
clean
: Clean the project, delete previous compilation results and files generated by the build.build
: Build the project, including compilation, testing, packaging and other operations.site
: Generate project documents and reports, such as test reports, code coverage reports, etc.
- Each stage contains some plug-ins and targets, which
Maven
are executed in a predefined order. For example, inbuild
a stage,Maven
the following goals are executed in sequence:validate
: Verify that the project is correct.compile
: Compile the project source code.test
: Run the test cases of the project.package
: Package the project into a jar or war file.verify
: Verify whether the packaging result is correct.install
: Install the packaging results to the local Maven repository.deploy
: Deploy the packaging results to the remote Maven repository.
idea
Download required plug-ins
EasyCode
Used to quickly generate database-related project directories and codes
MyBatisPlus
Used to jump between
java
andsql.xml
idea
Create project
ConfigurationServer URL
Address: https://start.aliyun.com/
Fill in project related information
Project creation successful (run and test)
idea
Test whether the connection is normalMySQL
Create database table
Add MySQL
configuration of connections within the project
Search for MySQL
dependency packages used by the connection
Write connection database configuration file
pom.xml
Introduce 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 EasyCode
to quickly create code related to operating databases
View the project directory structure after creation
Java
Applications typically use the following components to organize their code
The relationship between these components is usually call
Controller
,Service
definedService
withinimpl
the folder业务实现类
,业务实现类
callDAO
,DAO
operation , representing the database table structureMapper
SQL语句
Entity
实体类
Simply put,
Controller
it is used to receive user requests,Service
implement business logic,DAO
operate the database, andEntity
represent the database table structure.
/service/impl/xxx.java
Implement specific business logic inAdd statements
/resources/mapper/xxx.xml
to 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. UsuallySpring MVC
implemented using a framework.Service
: Service layer, used to implement business logic and call toDAO
perform data operations. Usually contains interface and implementation classes.DAO
: Data access object, used to operate the database. It is usually implemented using frameworksMyBatis
suchHibernate
as .Entity
: Entity class, used to represent the table structure in the database. Usually contains class attributes and correspondinggetter/setter
methods.
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)
<!-- <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 @MapperScan
annotations)
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
,@EnableAutoConfiguration
and@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-web
the 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
Solve the error (tell MyBatis
where to find SQL
the statement)
mybatis:
mapper-locations: classpath:**/mapper/*.xml
Rerun and request
Complete source code
Directory Structure
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>