来源:https://www.bilibili.com/video/BV1V7411w7VW
下一节:https://blog.csdn.net/qq_40893824/article/details/107344110
1 基本知识
ORMapping: Object Relationship Mapping 对象关系映射
对象:面向对象
关系:关系型数据库
Java 到 MySQL 的映射,开发者可用 面向对象的思想 管理理数据库
mybatis 优势:
相比 JDBC,代码减少
是持久化框架(瞬时数据,如内存中数据,它不能永久保存的,使之 持久化为持久数据)
sql 语句 写在 xml 文件中
mybatis 缺点:
依赖数据库,数据库不可以随意更换
2 新建工程
![](https://i-blog.csdnimg.cn/blog_migrate/b14c259b27ec2c32573e25c27a6806fc.png)
com.southwind
、mybatis
3 pom 文件
加入代码:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
<build>
部分:让系统可以扫描到 java 包中的 xml 文件,否则只能扫描到 resources 中的 xml 文件
4 数据库
datagrip:
use mybatis;
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
![](https://i-blog.csdnimg.cn/blog_migrate/9265d53e6fe9eb1c7398dc8a22bdeeea.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e3b972733b41a6833e2819c8f205fdb2.png)
5 新建实体类
java 中,创包 com.southwind.entity,其内新建 实体类,加入代码:
package com.southwind.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
private long id;
private String username;
private String password;
private int age;
}
![](https://i-blog.csdnimg.cn/blog_migrate/9aa17b0f6a0b5cd825c95f8ddc64c4eb.png)
6 配置文件
在 resources 中,新建 config.xml
加入代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置MyBatis运⾏行行环境 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务管理理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED配置JDBC数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</dataSource>
</environment>
</environments>
</configuration>
![](https://i-blog.csdnimg.cn/blog_migrate/ee4e4790b5130d82d7307a3ee1472396.png)
<environment id="a">
可以有多个,即多个数据库
在上面 <environments default="a">
指定 a 的数据库
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置MyBatis运⾏行行环境 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务管理理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED配置JDBC数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${driver-class-name}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</dataSource>
</environment>
</environments>
</configuration>
-----------------------
application.yml文件:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# test
url: jdbc:mysql://xxxxxxx:3306/bookmarksdb?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
username: dbAdmin
password: ENC(ato8fgnU10F****bFEL0ZIK18TJF)
server:
port: 8094
jasypt:
encryptor:
password: sad124f1f1rf1fgt5
property:
prefix: ENC(
suffix: )
7 mybatis 开发方式
1 原生接口
2 mapper 代理
7.1 法1 原生接口
mapper、config.xml、Test
1 southwind 中,创包 mapper,其内,新建 AccountMapper.xml,xml 文件是 file 型的,加入代码:
<?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.southwind.mapper.AccountMapper">
<!-- id 自定义;parameterType:传的参数 -->
<insert id="save" parameterType="com.southwind.entity.Account">
insert into t_account(username, password, age) values(#{username},#{password},#{age})
</insert>
</mapper>
![](https://i-blog.csdnimg.cn/blog_migrate/b05dcd30686fe173cdee4c774f800fc1.png)
参数 | 解释 |
---|---|
namespace | 文件所在包 + 文件名的形式 |
insert | 添加操作 |
select | 查询操作 |
update | 更新操作 |
delete | 删除操作 |
parameterType | 调用对应方法时参数的数据类型 |
2 resources/ config.xml 中,注册 AccountMapper.xml,加入代码:
<!-- 注册 AccountMapper.xml -->
<mappers>
<mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
</mappers>
![](https://i-blog.csdnimg.cn/blog_migrate/36681d099b27cb82a8b1d57698b1280c.png)
3 调用 mybatis 原生接口,执行 添加操作
southwind 中,创包 test,其内 新建 类 Test,加入代码:
package com.southwind.test;
import com.southwind.entity.Account;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class Test {
public static void main(String[] args) {
// 加载 mybatis 配置文件,读成流
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
// SqlSessionFactoryBuilder ( build() )→ SqlSessionFactory ( openSession() )→ SqlSession
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.southwind.mapper.AccountMapper.save";
Account account = new Account(1L, "张三", "123456", 22);
sqlSession.insert(statement, account);
sqlSession.commit();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/dcdefa6c43fb1192bb6789ae9e0a6d89.png)
运行:
添加成功!
7.2 法2 Mapper 接口
自定义接口、业务方法。
编写与方法相对应的 Mapper.xml
1 southwind 中,创包 repository,其内 新建 接口 AccountRepository,加入代码:
package com.southwind.repository;
import com.southwind.entity.Account;
import java.util.List;
public interface AccountRepository {
public int save(Account account);
public int update(Account account);
public int deleteById(long id);
public List<Account> findAll();
public Account findById(long id);
}
![](https://i-blog.csdnimg.cn/blog_migrate/ca1db7f9c4f0af0d52b2367bde17d494.png)
2 repository 中,新建 文件 AccountRepository.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.southwind.repository.AccountRepository">
<insert id="save" parameterType="com.southwind.entity.Account">
insert into t_account(username, password, age) values(#{username},#{password},#{age})
</insert>
<update id="update" parameterType="com.southwind.entity.Account">
update t_account set username=#{username},password=#{password},age=#{age} where id=#{id}
</update>
<delete id="deleteById" parameterType="long">
delete from t_account where id=#{id}
</delete>
<select id="findAll" resultType="com.southwind.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
select * from t_account where id=#{id}
</select>
</mapper>
![](https://i-blog.csdnimg.cn/blog_migrate/24f488cd381e81297ae7b01fc6ab14bb.png)
statement 标签 根据 SQL 执行的业务,选择 insert、delete、update、select
Mapper.xml规则:
namespace:接口的全类名
statement 的 id:接口中对应的方法名
statement 的 parameterType 和接口中对应方法的参数类型一致
statement 的 resultType 和接口中对应方法的返回值类型一致
3 config.xml 中注册 AccountRepository.xml,加入代码:
<!-- 注册AccountMapper.xml -->
<mapper resource="com/southwind/repository/AccountRepository.xml"></mapper>
![](https://i-blog.csdnimg.cn/blog_migrate/02b08ed2b428db685f968af8084ecec8.png)
增、删、查、改
4.1 test 中,新建类 Test2,加入代码:
全查询:
package com.southwind.test;
import com.southwind.entity.Account;
import com.southwind.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
// 查询
List<Account> list = accountRepository.findAll();
for (Account account:list){
System.out.println(account);
}
}
}
运行:
4.2 增
sqlSession.commit();
:提交事务
增、删、改 要提交事务
// 增
Account account = new Account(3L, "王五","123123",11);
int result = accountRepository.save(account);
sqlSession.commit();// 提交事务
![](https://i-blog.csdnimg.cn/blog_migrate/38110d015a3094c0eb1136ec1c8ae248.png)
运行:
4.3 id 查询
// id查
Account account = accountRepository.findById(2L);
System.out.println(account);
sqlSession.close();
![](https://i-blog.csdnimg.cn/blog_migrate/5dcbefb1a07838a8d3fe9565afc09794.png)
运行:
4.4 改
// 改
Account account = accountRepository.findById(2L);
account.setUsername("小米");
account.setPassword("qwe");
account.setAge(5);
int result = accountRepository.update(account);
sqlSession.commit();
System.out.println(result);
sqlSession.close();
![](https://i-blog.csdnimg.cn/blog_migrate/c8335d700c7d4cc5505013b35082555f.png)
运行:
1表示:有一行被修改了
数据库之前:
修改后:
4.5 删
// 删
int result = accountRepository.deleteById(2L);
System.out.println(result);
sqlSession.commit();
sqlSession.close();
![](https://i-blog.csdnimg.cn/blog_migrate/bb970e228213523349fb87d2481cb5c6.png)
运行:
1表示:有一行被删除了
id = 2L 的 那一行被删除了
下一节:https://blog.csdn.net/qq_40893824/article/details/107344110