CREATE DATABASE `mybatis` /*!40100 DEFAULT CHARACTER SET utf8mb4 */
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4
新建maven项目(quickstart模板)
添加mybatis依赖
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
然后要添加 资源文件的指定
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
resources>
build>
为什么要添加资源文件的指定?
来测试一下,不添加资源文件指定:
先clean以下之前编译结果,测试一下添加资源文件锁定后的编译结果:
jdbc.diverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=admin
SqlMapConfig.xml
先加入约束文件
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
核心配置文件内容:
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties">properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.diverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
<environment id="home">
<transactionManager type="">transactionManager>
<dataSource type="">dataSource>
environment>
<environment id="online">
<transactionManager type="">transactionManager>
<dataSource type="">dataSource>
environment>
environments>
configuration>
http://mybatis.org/dtd/mybatis-3-config.dtd 这个文档中规定了此配置文件中可以书写哪些标签
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
package org.example.pojo;
/**
* @Description:
* @Author:cjy
* @Data:2022/5/3
* @Version:
*/
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
/*
无参构造方法
*/
public Student() {
}
/*
全参的构造方法
*/
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
/*
不包括主键的构造方法
做增加操作时,主键不需要给值
*/
public Student(String name, String email, Integer age) {
this.name = name;
this.email = email;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
StudentMapper.xml
先加入约束头文件
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
映射文件的内容:
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="getAll" resultType="org.example.pojo.Student">
/*不使用*查询,因为*查询的效率极低*/
select id,name,email,age
from student
select>
mapper>
注意: 写完了映射文件之后,是无法直接使用映射文件的,还需要去核心配置文件中注册!!
在核心文件中注册:
<mappers>
<mapper resource="StudentMapper.xml">mapper>
mappers>
configuration>
http://mybatis.org/dtd/mybatis-3-mapper.dtd 这个文档中规定了此映射文件中可以书写哪些标签
<!ELEMENT mapper (cache-ref | cache | resultMap* | parameterMap* | sql* | insert* | update* | delete* | select* )+>
package org.example;
public class AppTest
{
@Test
public void test() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("test.getAll");
list.forEach(student -> System.out.println(student));//输出查询结果
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
}
为什么要用 List
因为查询结果是一个student对象,而mybatis会在底层帮我们将查询结果封装为一个对象放进list中。
注意,就算只查询一个字段,如name,返回结果依然是Student对象
如:
在映射文件中加入一条语句
<select id="getOneById" parameterType="_int" resultType="string">
select name
from student
where id=#{id}
select>
测试类:
@Test
public void test1() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
String name = sqlSession.selectOne("test.getOneById",1);
System.out.println(name);
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
映射文件:
<select id="getAll" resultType="org.example.pojo.Student">
select id,name,email,age
from student
select>
测试类:
@Test
public void test() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("test.getAll");
list.forEach(student -> System.out.println(student));//输出查询结果
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
<select id="getOneById" parameterType="_int" resultType="string">
select name
from student
where id=#{id}
select>
测试类:
@Test
public void test1() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
String name = sqlSession.selectOne("test.getOneById",1);
System.out.println(name);
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
映射文件:
<select id="getByName" parameterType="string" resultType="org.example.pojo.Student">
select id,name,email,age
from student
where name like '%${name}%'
select>
测试类:
@Test
public void test() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("test.getByName","张");
list.forEach(student -> System.out.println(student));//输出查询结果
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
映射文件:
<!--增加学生
int insert(Student stu)
-->
<insert id="insert" parameterType="org.example.pojo.Student">
insert into student (name,email,age)
values (#{name},#{email},#{age})
</insert>
测试类:
@Test
public void test() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//调用方法
int num = sqlSession.insert("test.insert",new Student(" 刘一","[email protected]",19));
//********************增删改之后,必须手动提交事务*********************
sqlSession.commit();
sqlSession.close();
}
<delete id="delete" parameterType="int">
delete from student
where id=#{id}
delete>
@Test
public void test2() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//调用方法
int num = sqlSession.delete("test.delete",5);
sqlSession.commit();
sqlSession.close();
}
<update id="update" parameterType="org.example.pojo.Student">
update student
set name=#{name},email=#{email},age=#{age}
where id=#{id}
update>
@Test
public void test2() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//调用方法
int num = sqlSession.update("test.update",new Student(4,"赵七","[email protected]",20));
sqlSession.commit();
sqlSession.close();
}
@Test
public void test() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("test.getAll");
list.forEach(student -> System.out.println(student));//输出查询结果
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
Resources类
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory 接口
SqlSessionFactoryBuilder类
build()
创建。SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession接口
Executor接口
没有简化前的测试代码:
@Test
public void test() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("test.getAll");
list.forEach(student -> System.out.println(student));//输出查询结果
//关闭sqlSession,还回数据库连接池
sqlSession.close();
}
先将固定写法部分封装为一个方法
//设置为全局变量
SqlSession sqlSession;
@Before //在所有@Test方法执行前先执行的方法
public void openSqlSession() throws IOException {
//使用文件流读取核心配置文件SqlMapConfig.xml
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession对象
sqlSession = factory.openSession();
}
@After
public void closeSqlSession(){
sqlSession.close();
}
其他测试方法的写法:
@Test
public void test() throws IOException {
//完成查询操作
List<Student> list = sqlSession.selectList("test.getAll");
list.forEach(student -> System.out.println(student));//输出查询结果
}
未优化前的映射文件的查询语句:
<select id="getAll" resultType="org.example.pojo.Student">
/*不使用*查询,因为*查询的效率极低*/
select id,name,email,age
from student
select>
在核心配置文件 SqlMapConfig.xml中去注册Student类的别名
<typeAliases>
<typeAlias type="org.example.pojo.Student" alias="student">typeAlias>
typeAliases>
然后就可以将映射文件中的 org.example.pojo.Student 更改为 student
<select id="getAll" resultType="student">
/*不使用*查询,因为*查询的效率极低*/
select id,name,email,age
from student
select>
当实体包下面的类有很多的时候(即数据库里面有很多张表),就用批量注册去注册这个包下的实体类的别名。
<typeAliases>
<package name="org.example.pojo"/>
typeAliases>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
运行下列测试代码:
@Test
public void test3() throws IOException {
//完成查询操作
List<Student> list = sqlSession.selectList("test.getAll");
list.forEach(student -> System.out.println(student));//输出查询结果
}