简介
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
快速起步
安装
如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
构建数据库
其对应的数据库 Schema 脚本如下:
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
其对应的数据库 Data 脚本如下:
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
构建实体类
使用了lombok插件
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
创建mybatis-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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mybatis/repository/UserRepository.xml"/>
</mappers>
</configuration>
- default = “”是哪个id,就是默认用哪个environment
- mappers是用来注册mapper的,下面会说到UserRepository,注意地址用“/”
- 填写上你相应的数据库信息,“&”需要由“&“替代
编写接口以及对应的xml
mybatis有原生接口和自定义接口两种方式,工作中只会使用自定义接口,因此不再赘述第一种
首先创建接口UserRepository
public interface UserRepository {
int save(User user);
int update(User user);
int deleteById(long id);
List<User> findAll();
User findById(long id);
}
顺便看一下我的目录结构
对应的xml,5个方法,增删改查
<?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.mybatis.repository.UserRepository">
<insert id="save" parameterType="com.example.mybatis.entity.User">
INSERT INTO user (id, name, age, email) VALUES (#{id}, #{name}, #{age}, #{email})
</insert>
<update id="update" parameterType="com.example.mybatis.entity.User">
update user set name = #{name},age = #{age},email = #{email} where id = #{id}
</update>
<delete id="deleteById" parameterType="long">
delete from user where id = #{id}
</delete>
<select id="findAll" resultType="com.example.mybatis.entity.User">
select * from user
</select>
<select id="findById" parameterType="long" resultType="com.example.mybatis.entity.User">
select * from user where id = #{id}
</select>
</mapper>
这里的xml就是mybatis-config.xml中注册的mapper,所有接口对应的xml文件都在mybatis-config.xml中进行注册。
需要注意
增删该查
对应的insert update delete select
要写对,不要增
的时候用select
等等
- namespace的值是相应接口的路径
- id的值是你接口的方法名
- parameterType的值是你传参的类型,如果是实体类,需要你引用类的路径
- reseltType的值是返回值的类型,通常
增删改
返回int,可以省略;一定要和接口中方法的返回值一样,不能方法写的Integer,reseltType的值写int
添加扫描
在pom.xml中添加以下,这样程序才能找到你接口对应的xml
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
测试
用测试类或者写一个main方法试试看
public class Main {
public static void main(String[] args) {
InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserRepository userRepository = sqlSession.getMapper(UserRepository.class);
// User user = new User(7L,"张三",18,"123@qq.com"); //增
// userRepository.save(user);
// userRepository.deleteById(7); //删
// User user = new User(6L,"张三",18,"123@qq.com"); //改
// userRepository.update(user);
// List<User> users = userRepository.findAll(); //查
// users.forEach(System.out::println);
// User user = userRepository.findById(1L); //查
// System.out.println(user);
sqlSession.commit();
sqlSession.close();
}
}
前4行代码的目的是为了创建出SqlSession对象,过程可以结合代码和图片来看。
到这里就完成了mybatis的快速起步,是不是很简单?而且如果你学会了springboot,结合mybatis后就会更加便捷,无需再手动创建SqlSession对象,目前大多数企业都是springboot+mybatis,一定要学好这两个框架。
有错误请及时指出。
Q.E.D.