版本 SpringBoot 版本是 2.7.4 MySQL版本是 8.0.28 ? 查看 MySQL 版本
select version();
? pom 引入依赖
- 添加 web,这是 spring 的 Web 开发框架
- 添加 MySQL 连接器依赖,注意没必要填写具体的 version,以免不必要的错误
- 添加 MyBatis-plus,目前最新版为 3.5.2
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
application 添加数据库配置
- testuseSSL:保障Internet数据传输安全利用数据加密,需要在url后面添加 useSSL=true 或者 false 不然在运行时控制台会出现红色警告
- serverTimezone:使用中国标准时间
- characterEncoding:指定字符编码
spring:
datasource:
url: "jdbc:mysql://192.168.140.22:3306/testuseSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8"
username: "root"
password: "mypassword"
实体 配置 UserPO,对应数据库表 user
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
public class UserPO {
private Integer id;
private String name;
private String password;
}
mapper 配置查询
- 继承 MyBatis-Plus 的 BaseMapper
@Repository
public interface IUserMapper extends BaseMapper<UserPO> {
}
service 配置查询
- 继承 MyBatis-Plus 的 ServiceImpl
@Service
public class UserService extends ServiceImpl<IUserMapper, UserPO> {
}
扫描路径
- 启动类配置 mapper 的 扫描路径(MapperScan)
@SpringBootApplication
@MapperScan("com.njc.java")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置自定义 xml
在 resources 新建 mapper 文件夹
<?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.njc.java.mapper.IUserMapper">
<select id="selectByName" resultType="com.njc.java.entity.UserPO">
select * from user where name= #{name}
</select>
</mapper>
@Repository
public interface IUserMapper extends BaseMapper<UserPO> {
UserPO selectByName(String name);
}
|