初级应用篇之MyBatis(一)Hello MyBatis
PupilYu 2019年03月25日
引入
用Maven来搭建项目,不集成Spring/Spring Boot,数据库使用Mysql。
我一般选择在Maven仓库中搜索库来找到依赖。
dependency如下:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
基本构成
MyBatis核心组件包括:
SqlSessionFactoryBuilder
SqlSessionFactory
SqlSession
mapper
先不说它们是干什么的,直接看代码,应用是最直观的认识
应用
Github地址:https://github.com/AngryPupil/BlogSource
项目目录结构:
数据库表:
create table student
(
id int(8) auto_increment primary key,
name varchar(8) not null,
age tinyint(2) not null,
constraint student_id_uindex unique (id)
);
核心配置文件 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>
<!-- 定义属性 -->
<properties>
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/pupil?characterEncoding=utf8&serverTimezone=GMT%2B8"/>
<property name="username" value="****"/>
<property name="password" value="****"/>
</properties>
<!-- 定义实体类别名,用于映射器(mapper)中引用 -->
<typeAliases>
<typeAlias alias="Student" type="net.pupil.mybatis.pojo.Student"/>
</typeAliases>
<!-- 配置环境,default默认启用id为development的数据源 -->
<environments default="development">
<environment id="development">
<!-- 数据库事务方式配置 -->
<transactionManager type="JDBC">
<!-- 配置为不自动提交 -->
<property name="autoCommit" value="false"/>
</transactionManager>
<!-- 数据源连接配置 -->
<dataSource type="POOLED">
<!-- 引用顶部定义的数据库连接属性 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射器配置文件 -->
<mappers>
<mapper resource="mybatis/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
根据配置文件构建SqlSessionFactory:
public class PupilSqlSessionFactory {
/**
* 单例模式,非多线程情景
*/
private static SqlSessionFactory sqlSessionFactory;
private PupilSqlSessionFactory() {
}
private static void init() {
if (sqlSessionFactory == null) {
String configPath = "mybatis/mybatis-config.xml";
try {
//读取配置文件
InputStream inputStream = Resources.getResourceAsStream(configPath);
//SqlSessionFactoryBuilder 根据配置文件信息生成 SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static SqlSessionFactory getFactoryInstance() {
init();
return sqlSessionFactory;
}
public static SqlSession openSession() {
init();
//sqlSessionFactory 开启会话来执行 SQL
return sqlSessionFactory.openSession();
}
}
实体类:
public class Student {
private Long id;
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Student(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
//省略setter/getter...
}
映射器:
public interface StudentMapper {
int insertStudent(Student student);
int deleteStudent(int age);
int updateStudent(Student student);
List<Student> selectAll();
Student selectById(Long id);
}
StudentMapper.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="net.pupil.mybatis.mapper.StudentMapper">
<insert id="insertStudent" parameterType="Student">
insert into student (name, age) values (#{name}, #{age});
</insert>
<delete id="deleteStudent">
<!-- <![CDATA[ ]]>为了注释掉大于小于等符号 -->
<![CDATA[
delete from student where age < #{age};
]]>
</delete>
<update id="updateStudent" parameterType="Student">
update student set name = #{name}, age = #{age} where id = #{id};
</update>
<select id="selectAll" resultType="Student">
select * from student;
</select>
<select id="selectById" resultType="Student">
select * from student where id = #{id};
</select>
</mapper>
测试:
public class TestMostBasic {
private static StudentMapper studentMapper;
public static void main(String[] args) {
SqlSession sqlSession = PupilSqlSessionFactory.openSession();
studentMapper = sqlSession.getMapper(StudentMapper.class);
testInsert();
testSelectAll();
testDelete();
testSelectAll();
testUpdate();
testSelectById();
sqlSession.commit();
sqlSession.close();
}
private static void testInsert() {
int retNum = studentMapper.insertStudent(new Student("Doncic", 20));
System.out.println("新增了" + retNum + "条");
studentMapper.insertStudent(new Student("Curry", 31));
studentMapper.insertStudent(new Student("Thompson", 29));
studentMapper.insertStudent(new Student("Durant", 31));
studentMapper.insertStudent(new Student("Nowitzki", 71));
}
private static void testDelete() {
int retNum = studentMapper.deleteStudent(30);
System.out.println("删除了" + retNum + "条");
}
private static void testUpdate() {
int retNum = studentMapper.updateStudent(new Student(10L, "Nowitzki", 41));
System.out.println("更改了" + retNum + "条");
}
private static void testSelectAll() {
List<Student> students = studentMapper.selectAll();
System.out.println(students);
}
private static void testSelectById() {
Student student = studentMapper.selectById(10L);
System.out.println(student);
}
}
运行日志:
新增了1条
[Student{id=6, name='Doncic', age=20}, Student{id=7, name='Curry', age=31}, Student{id=8, name='Thompson', age=29}, Student{id=9, name='Durant', age=31}, Student{id=10, name='Nowitzki', age=71}]
删除了2条
[Student{id=7, name='Curry', age=31}, Student{id=9, name='Durant', age=31}, Student{id=10, name='Nowitzki', age=71}]
更改了1条
Student{id=10, name='Nowitzki', age=41}
总结说明
这是一个最简单的MyBatis的Demo,基本步骤就是:
1.定义配置文件。
2.读取配置文件,利用 SqlSessionFactoryBuilder 根据配置文件生成 SqlSessionFactory。
3.通过 SqlSessionFactory 开启会话。
4.编写SQL,定义映射器
5.通过 SqlSession 获取对应 Mapper。
6.利用 Mapper 对数据进行增删改查。
参考:
MyBatis中文文档