目录
编写 Dao 接口 Mapper 映射文件 StudentDao.xml
一、三层架构
- 界面层(User Interface layer)
- 业务逻辑层(Business Logic Layer)
- 数据访问层(Data access layer)
1. 界面层(表示层,视图层):主要功能是接受用户的数据,显示请求的处理 结果。使用 web 页面和用户交互。
2. 业务逻辑层:接收表示传递过来的数据,检查数据,计算业务逻辑,调用数据访问层获取数据。
3. 数据访问层:与数据库打交道。主要实现对数据的增、删、改、查。将存储 在数据库中的数据提交给业务层,同时将业务层处理的数据保存到数据库
(2)、三层架构的优点
- 结构清晰、耦合度低, 各层分工明确
- 可维护性高,可扩展性高
- 有利于标准化
- 开发人员可以只关注整个结构中的其中某一层的功能实现
- 有利于各层逻辑的复用
二、使用 JDBC 的缺陷
public void findStudent() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//注册 mysql 驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据的基本信息 url ,username,password
String url = "jdbc:mysql://localhost:3306/springdb";
String username = "root";
String password = "123456";
//创建连接对象
conn = DriverManager.getConnection(url, username, password);
//保存查询结果
List<Student> stuList = new ArrayList<>();
//创建 Statement, 用来执行 sql 语句
stmt = conn.createStatement();
//执行查询,创建记录集,
rs = stmt.executeQuery("select * from student");
while (rs.next()) {
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setAge(rs.getInt("age"));
//从数据库取出数据转为 Student 对象,封装到 List 集合
stuList.add(stu);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭资源
if (rs != null) ;
{
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、快速入门
1、概述
2、解决的主要问题
- 减轻使用 JDBC 的复杂性,不用编写重复的创建 Connetion , Statement ;不用编写关闭资源代码。
- 直接使用 java 对象,表示结果数据。让开发者专注 SQL 的处理。
3、入门案例
添加Maven坐标
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
加入Maven插件
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
编写 Student 实体类
package com.hk.domain;
public class Student {
//属性名和列名一样
private Integer id;
private String name;
private String email;
private Integer age;
// set ,get , toString
}
编写 Dao 接口 StudentDao
package com.hk.dao;
import com.hk.domain.Student;
import java.util.List;
public interface StudentDao {
/*查询所有数据*/
List<Student> selectStudents();
}
编写 Dao 接口 Mapper 映射文件 StudentDao.xml
- 在 dao 包中创建文件 StudentDao.xml
- 要 StudentDao.xml 文件名称和接口 StudentDao 一样,区分大小写的一样。
<?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">
<!--
namespace:必须有值,自定义的唯一字符串
推荐使用:dao 接口的全限定名称
-->
<mapper namespace="com.hk.dao.StudentDao">
<!--
<select>: 查询数据, 标签中必须是 select 语句
id: sql 语句的自定义名称,推荐使用 dao 接口中方法名称,
使用名称表示要执行的 sql 语句
resultType: 查询语句的返回结果数据类型,使用全限定类名
-->
<select id="selectStudents" resultType="com.hk.domain.Student">
<!--要执行的 sql 语句-->
select id,name,email,age from student
</select>
</mapper>
创建 MyBatis 主配置文件
<?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="mysql">
<!--id:数据源的名称-->
<environment id="mysql">
<!--配置事务类型:使用 JDBC 事务(使用 Connection 的提交和回滚)-->
<transactionManager type="JDBC"/>
<!--数据源
dataSource:创建数据库 Connection 对象
type: POOLED 使用数据库的连接池
-->
<dataSource type="POOLED">
<!--连接数据库的四个要素-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--告诉 mybatis 要执行的 sql 语句的位置-->
<mapper resource="com/hk/dao/StudentDao.xml"/>
</mappers>
</configuration>
创建测试类 MyBatisTest
@Test
public void testStart() throws IOException {
//1.mybatis 主配置文件
String config = "mybatis-config.xml";
//2.读取配置文件
InputStream in = Resources.getResourceAsStream(config);
//3.创建 SqlSessionFactory 对象,目的是获取 SqlSession
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//4.获取 SqlSession,SqlSession 能执行 sql 语句
SqlSession session = factory.openSession();
//5.执行 SqlSession 的 selectList()
List<Student> studentList = session.selectList("com.hk.dao.StudentDao.selectStudents");
//6.循环输出查询结果
studentList.forEach( student -> System.out.println(student));
//7.关闭 SqlSession,释放资源
session.close();
}
List<Student> studentList = session.selectList("com.hk.dao.StudentDao.selectStudents");近似等价的 jdbc 代码Connection conn = 获取连接对象String sql=” select id,name,email,age from student”PreparedStatement ps = conn.prepareStatement(sql);ResultSet rs = ps.executeQuery();
配置日志功能
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
insert 操作
(1)StudentDao 接口中增加方法
int insertStudent(Student student);
(2)StudentDao.xml 加入 sql 语句
<insert id="insertStudent">
insert into student(id,name,email,age) values(#{id},#{name},#{email},#{age})
</insert>
(3)增加测试方法
@Test
public void testInsert() throws IOException {
//1.mybatis 主配置文件
String config = "mybatis-config.xml";
//2.读取配置文件
InputStream in = Resources.getResourceAsStream(config);
//3.创建 SqlSessionFactory 对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//4.获取 SqlSession
SqlSession session = factory.openSession();
//5.创建保存数据的对象
Student student = new Student();
student.setId(1005);
student.setName("张丽");
student.setEmail("zhangli@163.com");
student.setAge(20);
//6.执行插入 insert
int rows = session.insert("com.hk.dao.StudentDao.insertStudent",student);
//7.提交事务
session.commit();
System.out.println("增加记录的行数:"+rows);
//8.关闭 SqlSession
session.close();
}
4、MyBatis 对象分析
- openSession(true):创建一个有自动提交功能的 SqlSession
- openSession(false):创建一个非自动提交功能的 SqlSession,需手动提交
- openSession():同 openSession(false)
5、创建工具类
package com.hk.common;
public class MyBatisUtil {
//定义 SqlSessionFactory
private static SqlSessionFactory factory = null;
static {
//使用 静态块 创建一次 SqlSessionFactory
try{
String config = "mybatis-config.xml";
//读取配置文件
InputStream in = Resources.getResourceAsStream(config);
//创建 SqlSessionFactory 对象
factory = new SqlSessionFactoryBuilder().build(in);
}catch (Exception e){
factory = null;
e.printStackTrace();
}
}
/* 获取 SqlSession 对象 */
public static SqlSession getSqlSession(){
SqlSession session = null;
if( factory != null){
session = factory.openSession();
}
return session;
}
}
@Test
public void testUtils() throws IOException {
SqlSession session = MyBatisUtil.getSqlSession();
List<Student> studentList = session.selectList("com.hk.dao.StudentDao.selectStudents");
studentList.forEach( student -> System.out.println(student));
session.close();
}
6、MyBatis 使用传统 Dao 开发方式
Dao 开发
public class StudentDaoImpl implements StudentDao
(2)实现接口中 select 方法
public List<Student> selectStudents() {
SqlSession session = MyBatisUtil.getSqlSession();
List<Student> studentList = session.selectList("com.hk.dao.StudentDao.selectStudents");
session.close();
return studentList;
}
测试查询操作
@Test
public void testSelect() throws IOException {
StudentDao studentDao = new StudentDaoImpl();
final List<Student> studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
}
public int insertStudent(Student student) {
SqlSession session = MyBatisUtil.getSqlSession();
int nums = session.insert("com.hk.dao.StudentDao.insertStudent",student);
session.commit();
session.close();
return nums;
}
测试 insert
@Test
public void testInsert() throws IOException {
Student student = new Student();
student.setId(1006);
student.setName("林浩");
student.setEmail("linhao@163.com");
student.setAge(26);
int nums = studentDao.insertStudent(student);
System.out.println("使用 Dao 添加数据:"+nums);
}
传统 Dao 开发方式的分析
四、MyBatis 框架 Dao 代理
1、Dao 代理实现数据库操作
删除dao的实现类
(1)getMapper 获取代理对象
StudentDao studentDao = MyBatisUtil.getSqlSession().getMapper(StudentDao.class);
// getMapper()创建的对象,是代替我们自己创建的 StudentDaoImpl 类
(2)使用 Dao 代理对象方法执行 sql 语句
@Test
public void testSelect() throws IOException {
final List<Student> studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
}
insert 方法:
@Test
public void testInsert() throws IOException {
Student student = new Student();
student.setId(1006);
student.setName("林浩");
student.setEmail("linhao@163.com");
student.setAge(26);
int nums = studentDao.insertStudent(student);
System.out.println("使用 Dao 添加数据:"+nums);
}
2、深入理解参数
(1)parameterType
<delete id="deleteStudent" parameterType="int">
delete from student where id=#{studentId}
</delete>
等同于
<delete id="deleteStudent" parameterType="java.lang.Integer">
delete from student where id=#{studentId}
</delete>
(2)一个简单参数
Student selectById(int id);
mapper 文件:
<select id="selectById" resultType="com.hk.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
#{studentId} , studentId 是自定义的变量名称,和方法参数名无关。
@Test
public void testSelectById(){
//一个参数
Student student = studentDao.selectById(1005);
System.out.println("查询 id 是 1005 的学生:"+student);
}
(3)多个参数-使用@Param
List<Student> selectMultiParam(@Param("personName") String name,@Param("personAge") int age);
mapper 文件:
<select id="selectMultiParam" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student where name=#{personName} or age=#{personAge}
</select>
测试方法:
@Test
public void testSelectMultiParam(){
List<Student> stuList = studentDao.selectMultiParam("李力",20);
stuList.forEach( stu -> System.out.println(stu));
}
(4)多个参数-使用对象
package com.hk.vo;
public class QueryParam {
private String queryName;
private int queryAge;
//set ,get 方法
}
接口方法:
List<Student> selectMultiObject(QueryParam queryParam);
mapper 文件:
<select id="selectMultiObject" resultType="com.hk.domain.Student">
select id,name,email,age from student where name=#{queryName} or age=#{queryAge}
</select>
或
<select id="selectMultiObject" resultType="com.hk.domain.Student">
select id,name,email,age from student where name=#queryName,javaType=string,jdbcType=VARCHAR} or age =#queryAge,javaType=int,jdbcType=INTEGER}
</select>
测试方法:
@Test
public void selectMultiObject(){
QueryParam qp = new QueryParam();
qp.setQueryName("李力");
qp.setQueryAge(20);
List<Student> stuList = studentDao.selectMultiObject(qp);
stuList.forEach( stu -> System.out.println(stu));
}
(5)多个参数-按位置
List<Student> selectByNameAndAge(String name,int age);
mapper 文件
<select id="selectByNameAndAge" resultType="com.hk.domain.Student">
select id,name,email,age from student where name=#{arg0} or age=#{arg1}
</select>
测试方法:
@Test
public void testSelectByNameAndAge(){
//按位置参数
List<Student> stuList = studentDao.selectByNameAndAge("李力",20);
stuList.forEach( stu -> System.out.println(stu));
}
(6)多个参数-使用 Map
Map<String,Object> data = new HashMap<String,Object>();
data.put(“myname”,”李力”);
data.put(“myage”,20);
List<Student> selectMultiMap(Map<String,Object> map);
mapper 文件:
<select id="selectMultiMap" resultType="com.hk.domain.Student">
select id,name,email,age from student where name=#{myname} or age=#{myage}
</select>
测试方法:
@Test
public void testSelectMultiMap(){
Map<String,Object> data = new HashMap<>();
data.put("myname","李力");// #{myname}
data.put("myage",20); // #{myage}
List<Student> stuList = studentDao.selectMultiMap(data);
stuList.forEach( stu -> System.out.println(stu));
}
(7)#和$
- #:占位符,告诉 mybatis 使用实际的参数值代替。并使用PrepareStatement 对象执行 sql 语句, #{…}代替 sql 语句的“?”。这样做更安全,更迅速,通常也是首选做法,
<select id="selectById" resultType="com.hk.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
转为 MyBatis 的执行是:
String sql=” select id,name,email,age from student where id=?”;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1005);
解释:
- $ 字符串替换,告诉 mybatis 使用$包含的“字符串”替换所在位置。使用Statement 把 sql 语句和${}的内容连接起来。主要用在替换表名,列名,不同列排序等操作
Student findById(int id);
Student findByEmail(String email);
mapper 文件:
<select id="findById" resultType="com.hk.domain.Student">
select * from student where id=#{studentId}
</select>
<select id="findByEmail" resultType="com.hk.domain.Student">
select * from student where email=#{stuentEmail}
</select>
测试方法:
@Test
public void testFindStuent(){
Student student1 = studentDao.findById(1002);
System.out.println("findById:"+student1);
Student student2 = studentDao.findByEmail("zhou@126.net");
System.out.println("findByEmail:"+student2);
}
例 2:通用方法,使用不同列作为查询条件
Student findByDiffField(@Param("col") String colunName,@Param("cval") Object value);
<select id="findByDiffField" resultType="com.hk.domain.Student">
select * from student where ${col} = #{cval}
</select>
测试方法:
@Test
public void testFindDiffField(){
Student student1 = studentDao.findByDiffField("id",1002);
System.out.println("按 id 列查询:"+student1);
Student student2 = studentDao.findByDiffField("email","zhou@126.net");
System.out.println("按 email 列查询:"+student2);
}
3、MyBatis 输出结果
(1)resultType
- 简单类型
int countStudent();
mapper 文件:
<select id="countStudent" resultType="int">
select count(*) from student
</select>
测试方法:
@Test
public void testRetunInt(){
int count = studentDao.countStudent();
System.out.println("学生总人数:"+ count);
}
- 对象类型
Student selectById(int id);
<select id="selectById" resultType="com.hk.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
- Map
Map<Object,Object> selectReturnMap(int id);
mapper 文件:
<select id="selectReturnMap" resultType="java.util.HashMap">
select name,email from student where id = #{studentId}
</select>
测试方法:
@Test
public void testReturnMap(){
Map<Object,Object> retMap = studentDao.selectReturnMap(1002);
System.out.println("查询结果是 Map:"+retMap);
}
(2)resultMap
List<Student> selectUseResultMap(QueryParam param);
mapper 文件:
<!-- 创建 resultMap
id:自定义的唯一名称,在<select>使用
type:期望转为的 java 对象的全限定名称或别名
-->
<resultMap id="studentMap" type="com.hk.domain.Student">
<!-- 主键字段使用 id -->
<id column="id" property="id" />
<!--非主键字段使用 result-->
<result column="name" property="name"/>
<result column="email" property="email" />
<result column="age" property="age" />
</resultMap>
<!--resultMap: resultMap 标签中的 id 属性值-->
<select id="selectUseResultMap" resultMap="studentMap">
select id,name,email,age from student where name=#{queryName} or age=#{queryAge}
</select>
测试方法:
@Test
public void testSelectUseResultMap(){
QueryParam param = new QueryParam();
param.setQueryName("李力");
param.setQueryAge(20);
List<Student> stuList = studentDao.selectUseResultMap(param);
stuList.forEach( stu -> System.out.println(stu));
}
(3)实体类属性名和列名不同的处理方式
- 使用列别名和<resultType>
package com.hk.domain;
/**
* <p>Description: 实体类 </p>
*/
public class PrimaryStudent {
private Integer stuId;
private String stuName;
private Integer stuAge;
// set , get 方法
}
2. 接口方法
List<PrimaryStudent> selectUseFieldAlias(QueryParam param);
3. mapper 文件:
<select id="selectUseFieldAlias" resultType="com.hk.domain.PrimaryStudent">
select id as stuId, name as stuName,age as stuAge from student where name=#{queryName} or age=#{queryAge}
</select>
4.测试方法
@Test
public void testSelectUseFieldAlias(){
QueryParam param = new QueryParam();
param.setQueryName("李力");
param.setQueryAge(20);
List<PrimaryStudent> stuList;
stuList = studentDao.selectUseFieldAlias(param);
stuList.forEach( stu -> System.out.println(stu));
}
- 使用<resultMap>
List<PrimaryStudent> selectUseDiffResultMap(QueryParam param);
2. mapper 文件:
<!-- 创建 resultMap
id:自定义的唯一名称,在<select>使用
type:期望转为的 java 对象的全限定名称或别名
-->
<resultMap id="primaryStudentMap" type="com.hk.domain.PrimaryStudent">
<!-- 主键字段使用 id -->
<id column="id" property="stuId" />
<!--非主键字段使用 result-->
<result column="name" property="stuName"/>
<result column="age" property="stuAge" />
</resultMap>
<!--resultMap: resultMap 标签中的 id 属性值-->
<select id="selectUseDiffResultMap" resultMap="primaryStudentMap">
select id,name,email,age from student where name=#{queryName} or age=#{queryAge}
</select>
@Test
public void testSelectUseDiffResultMap(){
QueryParam param = new QueryParam();
param.setQueryName("李力");
param.setQueryAge(20);
List<PrimaryStudent> stuList;
stuList = studentDao.selectUseDiffResultMap(param);
stuList.forEach( stu -> System.out.println(stu));
}
(4)模糊 like
List<Student> selectLikeFirst(String name);
mapper 文件:
<select id="selectLikeFirst" resultType="com.hk.domain.Student">
select id,name,email,age from student where name like #{studentName}
</select>
@Test
public void testSelectLikeOne(){
String name="%力%";
List<Student> stuList = studentDao.selectLikeFirst(name);
stuList.forEach( stu -> System.out.println(stu));
}
例 2:mapper 文件中使用 like name "%" #{xxx} "%"
List<Student> selectLikeSecond(String name);
mapper 文件:
<select id="selectLikeSecond" resultType="com.hk.domain.Student">
select id,name,email,age from student where name like "%" #{studentName} "%"
</select>
测试方法:
@Test
public void testSelectLikeSecond(){
String name="力";
List<Student> stuList = studentDao.selectLikeSecond(name);
stuList.forEach( stu -> System.out.println(stu));
}
五、动态 SQL
< | 小于 | < |
> | 大于 | > |
>= | 大于等于 | >= |
<= | 小于等于 | <= |
1、<if>标签
List<Student> selectStudentIf(Student student);
<select id="selectStudentIf" resultType="com.hk.domain.Student">
select id,name,email,age from student where 1=1
<if test="name != null and name !='' ">
and name = #{name}
</if>
<if test="age > 0 ">
and age > #{age}
</if>
</select>
测试方法:
@Test
public void testSelect() throws IOException {
Student param = new Student();
param.setName("李力");
param.setAge(18);
List<Student> studentList = studentDao.selectStudentIf(param);
studentList.forEach( stu -> System.out.println(stu));
}
2、<where>
List<Student> selectStudentWhere(Student student);
mapper 文件:
<select id="selectStudentWhere" resultType="com.hk.domain.Student">
select id,name,email,age from student
<where>
<if test="name != null and name !='' ">
and name = #{name}
</if>
<if test="age > 0 ">
and age > #{age}
</if>
</where>
</select>
测试方法:
@Test
public void testSelectWhere() throws IOException {
Student param = new Student();
param.setName("李力");
param.setAge(18);
List<Student> studentList = studentDao.selectStudentWhere(param);
studentList.forEach( stu -> System.out.println(stu));
}
3、<foreach>
- collection 表示要遍历的集合类型, list ,array 等。
- open、close、separator 为对遍历内容的 SQL 拼接。
List<Student> selectStudentForList(List<Integer> idList);
mapper 文件:
<select id="selectStudentForList" resultType="com.hk.domain.Student">
select id,name,email,age from student
<if test="list !=null and list.size > 0 ">
where id in
<foreach collection="list" open="(" close=")" item="stuid" separator=",">
#{stuid}
</foreach>
</if>
</select>
测试方法:
@Test
public void testSelectForList() {
List<Integer> list = new ArrayList<>();
list.add(1002);
list.add(1005);
list.add(1006);
List<Student> studentList = studentDao.selectStudentForList(list);
studentList.forEach( stu -> System.out.println(stu));
}
(2)遍历 List<对象类型>
List<Student> selectStudentForList2(List<Student> stuList);
mapper 文件:
<select id="selectStudentForList2" resultType="com.hk.domain.Student">
select id,name,email,age from student
<if test="list !=null and list.size > 0 ">
where id in
<foreach collection="list" open="(" close=")" item="stuobject" separator=",">
#{stuobject.id}
</foreach>
</if>
</select>
@Test
public void testSelectForList2() {
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId(1002);
list.add(s1);
s1 = new Student();
s1.setId(1005);
list.add(s1);
List<Student> studentList = studentDao.selectStudentForList2(list);
studentList.forEach( stu -> System.out.println(stu));
}
4、代码片段
List<Student> selectStudentSqlFragment(List<Student> stuList);
mapper 文件:
<!--创建 sql 片段 id:片段的自定义名称-->
<sql id="studentSql">
select id,name,email,age from student
</sql>
<select id="selectStudentSqlFragment" resultType="com.hk.domain.Student">
<!-- 引用 sql 片段 -->
<include refid="studentSql"/>
<if test="list !=null and list.size > 0 ">
where id in
<foreach collection="list" open="(" close=")" item="stuobject" separator=",">
#{stuobject.id}
</foreach>
</if>
</select>
@Test
public void testSelectSqlFragment() {
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId(1002);
list.add(s1);
s1 = new Student();
s1.setId(1005);
list.add(s1);
List<Student> studentList = studentDao.selectStudentSqlFragment(list);
studentList.forEach( stu -> System.out.println(stu));
}
六、MyBatis 配置文件
1、主配置文件
- 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>
- 主要包含内容:
2、dataSource 标签
- UNPOOLED 不使用连接池的数据源
- POOLED 使用连接池的数据源
- JNDI 使用 JNDI 实现的数据源
dataSource 配置
<dataSource type="POOLED">
<!--连接数据库的四个要素-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?charset=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
MyBatis 在初始化时,根据<dataSource>的 type 属性来创建相应类型的数据源DataSource,即:
- type=”POOLED”:MyBatis 会创建 PooledDataSource 实例
- type=”UNPOOLED” : MyBatis 会创建 UnpooledDataSource 实例
- type=”JNDI”:MyBatis 会从 JNDI 服务上查找 DataSource 实例,然后返回使用
3、使用数据库属性配置文件


<dataSource type="POOLED">
<!--使用 properties 文件: 语法 ${key}-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
4、typeAliases(类型别名)
<typeAliases>
<!--
定义单个类型的别名
type:类型的全限定名称
alias:自定义别名
-->
<typeAlias type="com.bjpowernode.domain.Student" alias="mystudent"/>
<!--
批量定义别名,扫描整个包下的类,别名为类名(首字母大写或小写都可以)
name:包名
-->
<package name="com.bjpowernode.domain"/>
<package name="...其他包"/>
</typeAliases>
mapper.xml 文件,使用别名表示类型
<select id="selectStudents" resultType="mystudent">
select id,name,email,age from student
</select>
5、mappers(映射器)
七、PageHelper 分页
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
(2)加入 plugin 配置
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>
(3)PageHelper 对象
@Test
public void testSelect() throws IOException {
//获取第 1 页,3 条内容
PageHelper.startPage(1,3);
List<Student> studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
}