MyBatis基础
MyBatis快速入门
MyBatis相关API
MyBatis映射配置文件
MyBatis核心配置文件
MyBatis传统方式实现Dao层
框架介绍:
框架是一款半成品软件,我们可以基于这个半成品软件继续开发。来完成我们个性化的需求!
ORM 介绍
ORM(Object relational Mapping):兑对象关系映射
指的是持久化数据和实体对象的映射模式,为了解决面向对象与关系型数据库存在的互不匹配的现象的技术
映射规则:
数据表---》类
表字段---》类属性
表数据---》对象
MyBatis介绍
原始JDBC的操作-查询
原始JDBC的操作-新增
原始JDBC的操作问题分析
1,频繁创建和销毁数据库的连接会造成系统资源浪费从而影响系统性能
2,sql语句在代码中硬编码,如果要修改sql语句,就需要修改java代码,造成代码不易维护
3,查询操作时,需要手动将结果集中的数据封装到实体对象中
4,增删改查操作需要参数时,需要手动将实体对象的数据设置到sql语句的占位符
原始JDBC的操作问题解决方案
1.使用数据库连接池初始化连接资源。
2.将sql语句抽取到配置文件中。
3.使用反射,内省等底层技术,将实体与表进行属性与字段的自动映射
MyBatis是一个优秀的基于Java的持久层框架,它内部封装了JDBC,使开发者只需要关注SQL语句本身,
而不需要花费精力去处理加载驱动,创建连接,创建执行者等复杂的操作。
MyBatis通过xml或注解的方式将要执行的各种Statement配置起来,并通过Java对象和Statement中SQL的动态参数进行映射生成最终要执行的SQL语句。
最后MyBatis框架执行完SQL并将结果返回映射为Java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对JDBC进行了封装,屏蔽了JDBC API底层访问细节,是我们不用与JDBC API打交道,就可以完成对数据库的持久化操作。
MyBatis入门程序
1.数据准备
2.导入jar包
3.在src下创建映射配置文件
4.在src下创建核心配置文件
5.编写测试类完成相关API的使用
6.运行测试查看结果
目录结构
导入三个包
src代码如下
bean中Student代码
package com.itheima.bean; public class Student { private Integer id; private String name; private Integer age; public Student() { } public Student(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
dao中StudentTest01代码
package com.itheima.dao; import com.itheima.bean.Student; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.InputStream; import java.util.List; public class StudentTest01 { /* 查询全部 */ @Test public void selectAll() throws Exception{ //1.加载核心配置文件 //InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); InputStream is = StudentTest01.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过SqlSession工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //4.执行映射配置文件中的sql语句,并接收结果 List<Student> list = sqlSession.selectList("StudentMapper.selectAll"); //5.处理结果 for (Student stu : list) { System.out.println(stu); } //6.释放资源 sqlSession.close(); is.close(); } }
MyBatisConfig.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="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.23.129:3306/db3"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="StudentMapper.xml"></mapper> </mappers> </configuration>
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="StudentMapper"> <select id="selectAll" resultType="com.itheima.bean.Student"> Select * FROM Student </select> </mapper>
快速入门小结
1.框架
框架是一款半成品软件,我们可以基于框架继续开发,从而完成一些个性化的需求。
2.ORM
对象关系映射,数据和实体对象的映射
3.MyBatis
是一个优秀的基于Java的持久层框架,它内部封装了JDBC。
4.入门步骤
导jar包
编写映射配置文件。
编写核心配置文件。
使用想相应的API来完成编码。
MyBatis相关API
Resources
org.apache.ibatis.io.Resources:加载资源的工具类。
核心方法
返回值 方法名 说明
InputStream getResourceAsStream(String fileName) 通过类加载器返回指定资源的字节输入流
SqlSessionFactoryBuilder
org.apache.ibatis.session.SqlSessionFactoryBuilder:获取SqlSessionFactory工厂对象的功能类
返回值 方法名 说明
SqlSessionFactory build(InputStream is) 通过指定资源字节输入流获取SqlSession工厂对象
SqlSessionFactory
org.apache.ibatis.session.SqlSessionFactory:获取SqlSession构建者对象的工厂接口。
核心方法
返回值 方法名 说明
SqlSession openSession() 获取SqlSession构建者对象,并开启手动提交事务
SqlSession openSession(boolean autoCommit) 获取SqlSession构建者对象,如果参数为true,则开启自动提交事务
SqlSession
org.apache.ibatis.session.SqlSessio:构建者对象接口。用于执行SQL,管理事务,接口代理。
核心api
相关API小结
Resources
加载资源的工具类。
SqlSessionFactoryBuilder
获取SqlSessionFactory工厂对象的功能类。
SqlSessionFactory
获取SqlSession构建者对象的工厂接口
指定事务的提交方式
SqlSession
构建者对象接口
执行SQL
管理事务
接口代理
MyBatis映射配置文件
映射配置文件介绍
映射配置文件包含了数据和对象之间的映射关系以及要执行的SQL语句。
查询功能
<select>
属性
id: 唯一标识,配合名称空间使用
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型。
SQL获取参数
#{属性名}
StudentMapper中添加
<select id="selectById" resultType="com.itheima.bean.Student" parameterType="java.lang.Integer"> Select * FROM Student where id = #{id} </select>
StudentTest测试类中
/* * 根据id查询 * */ @Test public void selectById() throws Exception{ //1.记载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //4.执行映射配置文件中的sql语句,并接受结果 Student stu = sqlSession.selectOne("StudentMapper.selectById",3); //5.处理结果 System.out.println(stu); //6.释放资源 sqlSession.close(); is.close(); }
新增功能
<insert>:新增功能标签
属性
id:唯一标识,配合名称空间使用。
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
StudentMapper中添加
<insert id="insert" parameterType="com.itheima.bean.Student"> Insert into Student values(#{id},#{name},#{age}) </insert>
StudentTest测试类中
/* * 新增功能 * * */ @Test public void insert() throws Exception{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.执行映射文件中的sql语句 Student stu=new Student(5,"周气",27); int insert = sqlSession.insert("StudentMapper.insert", stu); //5.提交事务 //sqlSession.commit(); //6.处理结果 System.out.println(insert); //7.关闭资源 sqlSession.close(); is.close(); }
修改功能
<update>:修改功能标签
属性
id:唯一标识,配合名称空间使用。
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
StudentMapper中添加
<update id="update" parameterType="com.itheima.bean.Student"> update Student set name =#{name},age=#{age} where id=#{id} </update>
StudentTest测试类中
/* * 修改功能 * */ @Test public void update() throws Exception{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.执行映射文件中的sql语句 Student stu=new Student(5,"李气",30); int insert = sqlSession.update("StudentMapper.update", stu); //5.提交事务 //sqlSession.commit(); //6.处理结果 System.out.println(insert); //7.关闭资源 sqlSession.close(); is.close(); }
删除功能
<delete>:删除功能标签
属性
id:唯一标识,配合名称空间使用。
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
StudentMapper中添加
<delete id="delete" parameterType="java.lang.Integer"> delete from Student where id=#{id} </delete>
StudentTest测试类中
/* * 删除功能 * */ @Test public void delete() throws Exception{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.执行映射文件中的sql语句 int result = sqlSession.delete("StudentMapper.delete", 5); //5.提交事务 //sqlSession.commit(); //6.处理结果 System.out.println(result); //7.关闭资源 sqlSession.close(); is.close(); }
映射配置文件小结
映射配置文件包含了数据和对象之间的映射关系以及要执行的SQL语句。
<mapper>:核心根标签
namespace属性:名称空间
<select>:查询功能标签
<insert>:新增功能标签
<update>:修改功能标签
<delete>:删除功能标签
id属性:唯一标识,配合名称空间使用
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
核心配置文件的介绍
核心配置文件包含了MyBatis最核心的设置和属性信息。如数据库的连接,事务,连接池等。
<?xml version="1.0" encoding="UTF-8" ?> <!--MyBatis的DTD约束--> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration 核心根标签--> <configuration> <!--environments配置数据库环境,环境可以有多个 default属性指定我们使用的是哪个--> <environments default="mysql"> <!--配置数据库环境 id属性唯一标识--> <environment id="mysql"> <!--transactionManager事务管理。type属性,采用JDBC默认的事务处理--> <transactionManager type="JDBC"></transactionManager> <!--dataSource数据源信息 type属性 连接池--> <dataSource type="POOLED"> <!--property获取数据库连接的配置信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.23.129:3306/db3"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--mappers引入映射配置文件--> <mappers> <!--mapper引入指定的映射配置文件 resource属性指定映射配置文件的名称--> <mapper resource="StudentMapper.xml"></mapper> </mappers> </configuration>
数据库连接配置文件的引入
<properties>:引入数据库连接配置文件标签
属性
resource:数据库连接配置文件路径
获取数据库连接参数
${键名}
------------恢复内容结束------------
------------恢复内容开始------------
MyBatis快速入门
MyBatis相关API
MyBatis映射配置文件
MyBatis核心配置文件
MyBatis传统方式实现Dao层
框架介绍:
框架是一款半成品软件,我们可以基于这个半成品软件继续开发。来完成我们个性化的需求!
ORM 介绍
ORM(Object relational Mapping):兑对象关系映射
指的是持久化数据和实体对象的映射模式,为了解决面向对象与关系型数据库存在的互不匹配的现象的技术
映射规则:
数据表---》类
表字段---》类属性
表数据---》对象
MyBatis介绍
原始JDBC的操作-查询
原始JDBC的操作-新增
原始JDBC的操作问题分析
1,频繁创建和销毁数据库的连接会造成系统资源浪费从而影响系统性能
2,sql语句在代码中硬编码,如果要修改sql语句,就需要修改java代码,造成代码不易维护
3,查询操作时,需要手动将结果集中的数据封装到实体对象中
4,增删改查操作需要参数时,需要手动将实体对象的数据设置到sql语句的占位符
原始JDBC的操作问题解决方案
1.使用数据库连接池初始化连接资源。
2.将sql语句抽取到配置文件中。
3.使用反射,内省等底层技术,将实体与表进行属性与字段的自动映射
MyBatis是一个优秀的基于Java的持久层框架,它内部封装了JDBC,使开发者只需要关注SQL语句本身,
而不需要花费精力去处理加载驱动,创建连接,创建执行者等复杂的操作。
MyBatis通过xml或注解的方式将要执行的各种Statement配置起来,并通过Java对象和Statement中SQL的动态参数进行映射生成最终要执行的SQL语句。
最后MyBatis框架执行完SQL并将结果返回映射为Java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对JDBC进行了封装,屏蔽了JDBC API底层访问细节,是我们不用与JDBC API打交道,就可以完成对数据库的持久化操作。
MyBatis入门程序
1.数据准备
2.导入jar包
3.在src下创建映射配置文件
4.在src下创建核心配置文件
5.编写测试类完成相关API的使用
6.运行测试查看结果
目录结构
导入三个包
src代码如下
bean中Student代码
package com.itheima.bean; public class Student { private Integer id; private String name; private Integer age; public Student() { } public Student(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
dao中StudentTest01代码
package com.itheima.dao; import com.itheima.bean.Student; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.InputStream; import java.util.List; public class StudentTest01 { /* 查询全部 */ @Test public void selectAll() throws Exception{ //1.加载核心配置文件 //InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); InputStream is = StudentTest01.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过SqlSession工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //4.执行映射配置文件中的sql语句,并接收结果 List<Student> list = sqlSession.selectList("StudentMapper.selectAll"); //5.处理结果 for (Student stu : list) { System.out.println(stu); } //6.释放资源 sqlSession.close(); is.close(); } }
MyBatisConfig.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="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.23.129:3306/db3"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="StudentMapper.xml"></mapper> </mappers> </configuration>
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="StudentMapper"> <select id="selectAll" resultType="com.itheima.bean.Student"> Select * FROM Student </select> </mapper>
快速入门小结
1.框架
框架是一款半成品软件,我们可以基于框架继续开发,从而完成一些个性化的需求。
2.ORM
对象关系映射,数据和实体对象的映射
3.MyBatis
是一个优秀的基于Java的持久层框架,它内部封装了JDBC。
4.入门步骤
导jar包
编写映射配置文件。
编写核心配置文件。
使用想相应的API来完成编码。
MyBatis相关API
Resources
org.apache.ibatis.io.Resources:加载资源的工具类。
核心方法
返回值 方法名 说明
InputStream getResourceAsStream(String fileName) 通过类加载器返回指定资源的字节输入流
SqlSessionFactoryBuilder
org.apache.ibatis.session.SqlSessionFactoryBuilder:获取SqlSessionFactory工厂对象的功能类
返回值 方法名 说明
SqlSessionFactory build(InputStream is) 通过指定资源字节输入流获取SqlSession工厂对象
SqlSessionFactory
org.apache.ibatis.session.SqlSessionFactory:获取SqlSession构建者对象的工厂接口。
核心方法
返回值 方法名 说明
SqlSession openSession() 获取SqlSession构建者对象,并开启手动提交事务
SqlSession openSession(boolean autoCommit) 获取SqlSession构建者对象,如果参数为true,则开启自动提交事务
SqlSession
org.apache.ibatis.session.SqlSessio:构建者对象接口。用于执行SQL,管理事务,接口代理。
核心api
相关API小结
Resources
加载资源的工具类。
SqlSessionFactoryBuilder
获取SqlSessionFactory工厂对象的功能类。
SqlSessionFactory
获取SqlSession构建者对象的工厂接口
指定事务的提交方式
SqlSession
构建者对象接口
执行SQL
管理事务
接口代理
MyBatis映射配置文件
映射配置文件介绍
映射配置文件包含了数据和对象之间的映射关系以及要执行的SQL语句。
查询功能
<select>
属性
id: 唯一标识,配合名称空间使用
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型。
SQL获取参数
#{属性名}
StudentMapper中添加
<select id="selectById" resultType="com.itheima.bean.Student" parameterType="java.lang.Integer"> Select * FROM Student where id = #{id} </select>
StudentTest测试类中
/* * 根据id查询 * */ @Test public void selectById() throws Exception{ //1.记载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //4.执行映射配置文件中的sql语句,并接受结果 Student stu = sqlSession.selectOne("StudentMapper.selectById",3); //5.处理结果 System.out.println(stu); //6.释放资源 sqlSession.close(); is.close(); }
新增功能
<insert>:新增功能标签
属性
id:唯一标识,配合名称空间使用。
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
StudentMapper中添加
<insert id="insert" parameterType="com.itheima.bean.Student"> Insert into Student values(#{id},#{name},#{age}) </insert>
StudentTest测试类中
/* * 新增功能 * * */ @Test public void insert() throws Exception{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.执行映射文件中的sql语句 Student stu=new Student(5,"周气",27); int insert = sqlSession.insert("StudentMapper.insert", stu); //5.提交事务 //sqlSession.commit(); //6.处理结果 System.out.println(insert); //7.关闭资源 sqlSession.close(); is.close(); }
修改功能
<update>:修改功能标签
属性
id:唯一标识,配合名称空间使用。
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
StudentMapper中添加
<update id="update" parameterType="com.itheima.bean.Student"> update Student set name =#{name},age=#{age} where id=#{id} </update>
StudentTest测试类中
/* * 修改功能 * */ @Test public void update() throws Exception{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.执行映射文件中的sql语句 Student stu=new Student(5,"李气",30); int insert = sqlSession.update("StudentMapper.update", stu); //5.提交事务 //sqlSession.commit(); //6.处理结果 System.out.println(insert); //7.关闭资源 sqlSession.close(); is.close(); }
删除功能
<delete>:删除功能标签
属性
id:唯一标识,配合名称空间使用。
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
StudentMapper中添加
<delete id="delete" parameterType="java.lang.Integer"> delete from Student where id=#{id} </delete>
StudentTest测试类中
/* * 删除功能 * */ @Test public void delete() throws Exception{ //加载核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(true); //4.执行映射文件中的sql语句 int result = sqlSession.delete("StudentMapper.delete", 5); //5.提交事务 //sqlSession.commit(); //6.处理结果 System.out.println(result); //7.关闭资源 sqlSession.close(); is.close(); }
映射配置文件小结
映射配置文件包含了数据和对象之间的映射关系以及要执行的SQL语句。
<mapper>:核心根标签
namespace属性:名称空间
<select>:查询功能标签
<insert>:新增功能标签
<update>:修改功能标签
<delete>:删除功能标签
id属性:唯一标识,配合名称空间使用
parameterType:指定参数映射的对象类型
resultType:指定结果映射的对象类型
SQL获取参数
#{属性名}
核心配置文件的介绍
核心配置文件包含了MyBatis最核心的设置和属性信息。如数据库的连接,事务,连接池等。
<?xml version="1.0" encoding="UTF-8" ?> <!--MyBatis的DTD约束--> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration 核心根标签--> <configuration> <!--environments配置数据库环境,环境可以有多个 default属性指定我们使用的是哪个--> <environments default="mysql"> <!--配置数据库环境 id属性唯一标识--> <environment id="mysql"> <!--transactionManager事务管理。type属性,采用JDBC默认的事务处理--> <transactionManager type="JDBC"></transactionManager> <!--dataSource数据源信息 type属性 连接池--> <dataSource type="POOLED"> <!--property获取数据库连接的配置信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.23.129:3306/db3"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--mappers引入映射配置文件--> <mappers> <!--mapper引入指定的映射配置文件 resource属性指定映射配置文件的名称--> <mapper resource="StudentMapper.xml"></mapper> </mappers> </configuration>
数据库连接配置文件的引入
<properties>:引入数据库连接配置文件标签
属性
resource:数据库连接配置文件路径
获取数据库连接参数
${键名}
jdbc.properties文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://192.168.23.129:3306/db3 username=root password=root
MyBatisConfig.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!--MyBatis的DTD约束--> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration 核心根标签--> <configuration> <!--引入数据库连接的配置文件--> <properties resource="jdbc.properties"/> <!--environments配置数据库环境,环境可以有多个 default属性指定我们使用的是哪个--> <environments default="mysql"> <!--配置数据库环境 id属性唯一标识--> <environment id="mysql"> <!--transactionManager事务管理。type属性,采用JDBC默认的事务处理--> <transactionManager type="JDBC"></transactionManager> <!--dataSource数据源信息 type属性 连接池--> <dataSource type="POOLED"> <!--property获取数据库连接的配置信息--> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--mappers引入映射配置文件--> <mappers> <!--mapper引入指定的映射配置文件 resource属性指定映射配置文件的名称--> <mapper resource="StudentMapper.xml"></mapper> </mappers> </configuration>
起别名:
<typeAliases>:为全类名起别名的父标签
<typeAlias>:为全类名起别名的子标签
属性:
type:指定全类名
alias:指定别名
<package>:为指定包下所有类起别名的子标签。(别名就是类名)
MyBatisConfig.xml加入
<!--起别名--> <typeAliases> <typeAlias type="com.itheima.bean.Student" alias="student"></typeAlias> <!--<package name="com.itheima.bean"/>--> </typeAliases>
StudentMapper.xml文件为
<?xml version="1.0" encoding="UTF-8" ?> <!--MyBatis的DTD约束--> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- mapper:核心根标签 namespace属性:名称空间 --> <mapper namespace="StudentMapper"> <!-- select:查询功能的标签 id属性:唯一标识 resultType属性:指定结果映射对象的类型 parameterType:指定参数映射对象类型 --> <select id="selectAll" resultType="student"> Select * FROM Student </select> <select id="selectById" resultType="student" parameterType="int"> Select * FROM Student where id = #{id} </select> <insert id="insert" parameterType="student"> Insert into Student values(#{id},#{name},#{age}) </insert> <update id="update" parameterType="student"> update Student set name =#{name},age=#{age} where id=#{id} </update> <delete id="delete" parameterType="int"> delete from Student where id=#{id} </delete> </mapper>
核心配置文件小结
核心配置文件包含了MyBatis最核心的设置和属性信息。如数据库的连接,事务,连接池信息等
MyBatis传统方式实现Dao层
Dao层传统实现方式
分层思想:控制层(controller),业务层(service),持久层(dao)
MyBatis目录结构
mapper包下
持久层接口
StudentMapper
package com.itheima.mapper; import com.itheima.bean.Student; import java.util.List; /* * 持久层接口 * */ public interface StudentMapper { //查询全部 public abstract List<Student> selectAll(); //根据id查询 public abstract Student selectById(Integer id); //新增数据 public abstract Integer insert(Student stu); //修改数据 public abstract Integer update(Student stu); //删除数据 public abstract Integer delete(Integer id); }
持久层接口实现类
package com.itheima.mapper.impl; import com.itheima.bean.Student; import com.itheima.mapper.StudentMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; /* 持久层实现类 */ public class StudentMapperImpl implements StudentMapper { /* 查询全部 */ @Override public List<Student> selectAll() { List<Student> list = null; SqlSession sqlSession = null; InputStream is = null; try{ //1.加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); //4.执行映射配置文件中的sql语句,并接收结果 list = sqlSession.selectList("StudentMapper.selectAll"); } catch (Exception e) { e.printStackTrace(); } finally { //5.释放资源 if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //6.返回结果 return list; } /* 根据id查询 */ @Override public Student selectById(Integer id) { Student stu = null; SqlSession sqlSession = null; InputStream is = null; try{ //1.加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); //4.执行映射配置文件中的sql语句,并接收结果 stu = sqlSession.selectOne("StudentMapper.selectById",id); } catch (Exception e) { e.printStackTrace(); } finally { //5.释放资源 if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //6.返回结果 return stu; } /* 新增功能 */ @Override public Integer insert(Student stu) { Integer result = null; SqlSession sqlSession = null; InputStream is = null; try{ //1.加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); //4.执行映射配置文件中的sql语句,并接收结果 result = sqlSession.insert("StudentMapper.insert",stu); } catch (Exception e) { e.printStackTrace(); } finally { //5.释放资源 if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //6.返回结果 return result; } /* 修改功能 */ @Override public Integer update(Student stu) { Integer result = null; SqlSession sqlSession = null; InputStream is = null; try{ //1.加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); //4.执行映射配置文件中的sql语句,并接收结果 result = sqlSession.update("StudentMapper.update",stu); } catch (Exception e) { e.printStackTrace(); } finally { //5.释放资源 if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //6.返回结果 return result; } /* 删除功能 */ @Override public Integer delete(Integer id) { Integer result = null; SqlSession sqlSession = null; InputStream is = null; try{ //1.加载核心配置文件 is = Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(true); //4.执行映射配置文件中的sql语句,并接收结果 result = sqlSession.delete("StudentMapper.delete",id); } catch (Exception e) { e.printStackTrace(); } finally { //5.释放资源 if(sqlSession != null) { sqlSession.close(); } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //6.返回结果 return result; } }
service业务层包下
业务层接口StudentService
package com.itheima.service; import com.itheima.bean.Student; import java.util.List; /* 业务层接口 */ public interface StudentService { //查询全部 public abstract List<Student> selectAll(); //根据id查询 public abstract Student selectById(Integer id); //新增数据 public abstract Integer insert(Student stu); //修改数据 public abstract Integer update(Student stu); //删除数据 public abstract Integer delete(Integer id); }
service实现类StudentServiceImpl
package com.itheima.service.impl; import com.itheima.bean.Student; import com.itheima.mapper.StudentMapper; import com.itheima.mapper.impl.StudentMapperImpl; import com.itheima.service.StudentService; import java.util.List; /* 业务层实现类 */ public class StudentServiceImpl implements StudentService { //创建持久层对象 private StudentMapper mapper = new StudentMapperImpl(); @Override public List<Student> selectAll() { return mapper.selectAll(); } @Override public Student selectById(Integer id) { return mapper.selectById(id); } @Override public Integer insert(Student stu) { return mapper.insert(stu); } @Override public Integer update(Student stu) { return mapper.update(stu); } @Override public Integer delete(Integer id) { return mapper.delete(id); } }
StudentController控制层
package com.itheima.controller; import com.itheima.bean.Student; import com.itheima.service.StudentService; import com.itheima.service.impl.StudentServiceImpl; import org.junit.Test; import java.util.List; /* 控制层测试类 */ public class StudentController { //创建业务层对象 private StudentService service = new StudentServiceImpl(); //查询全部功能测试 @Test public void selectAll() { List<Student> students = service.selectAll(); for (Student stu : students) { System.out.println(stu); } } //根据id查询功能测试 @Test public void selectById() { Student stu = service.selectById(3); System.out.println(stu); } //新增功能测试 @Test public void insert() { Student stu = new Student(4,"赵六",26); Integer result = service.insert(stu); System.out.println(result); } //修改功能测试 @Test public void update() { Student stu = new Student(4,"赵六",16); Integer result = service.update(stu); System.out.println(result); } //删除功能测试 @Test public void delete() { Integer result = service.delete(4); System.out.println(result); } }
LOG4J
在日常开发过程中,排查问题时难免需要输出MyBatis真正执行的SQL语句,结果,参数等信息,我们就可以借助LOG4J的功能来实现执行信息的输出。
使用步骤:
1.导入jar包
2.修改核心配置文件
在MyBatisConfig.xml上加入
<!--集成LOG4J日志信息--> <setting> <setting name="logImpl" value="log4j"/> </setting>
3.在src下编写LOG4J配置文件
#ERROR 错误信息
WARN警告信息
INFO 普通信息
DEBUG
stdout:把信息输出到控制台上
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%nz