1Mybatis
心无明日之人 怕是今日也过不好
一、概述
1. 开发常用架构
① 三层架构
- 1)三层架构
- 界面层(controller):和用户打交道,显示处理结果。如:servlet、html、jsp
- 业务逻辑层(service):界面层传递数据,计算逻辑,调用数据库
- 数据访问层(dao):访问数据库
- 2)三层架构对应的框架
- 界面层:servlet — spring mvc
- 业务逻辑层:service — spring
- 数据访问层:dao — mybatis
2. 框架
- 1)框架:框架是一个舞台,一个模板。半成品软件
- 2)框架是一个模块
- 框架定义好一些功能。这些功能是可用的
- 可以加入项目中自己的功能,这些功能可以利用框架中写好的功能
- 3)框架特点:
- 一般不是全能的
- 框架针对某一个领域有效,特长在某一个方面
3. JDBC缺陷
- 代码多,开发效率低
- 需要关注Connection、Statement、ResultSet对象的销毁
- 对ResultSet查询的结果,需要自己封装
- 重复代码多
- 业务代码和数据库操作混合在一起
4. 持久层技术解决方案
- 1)jdbc技术
- 2)Spring的JdbcTemplate:spring对jdbc的简单封装
- 3)Apache的DBUtils:与spring的JdbcTemplate类似
- 以上都不是框架,(2)、(3)都只是工具类
5. mybatis
- 1)Mybatis提供了数据库操作的基本功能。早期叫做iBatis。代码在github
- 2)mybatis是
mybatis sql mapper framwork for java
(sql映射框架) - 3)mybatis的作用:
sql mapper
:sql映射。- 可以把数据库表中的一行数据,映射为一个java对象。操作这个对象,就相当于操作数据库表。ORM
data access objects(DAOs)
:数据访问,对数据增删查改。
- 4)提供的功能
- 提供了创建Connection、Statement、RrsultSet的能力,不需要开发人员创建
- 提供了执行sql的能力
- 提供了循环sql,转为对象的功能
- 提供了关闭资源功能
- 5)总结:mybatis是一个sql映射框架,提供了数据库的操作能力。增强的JDBC。让开发人员集中精力写sql就行,不必关心Connection、Statement、ResultSet的创建、关闭和sql的执行
注意:实体类的属性和数据库的字段名保持一致
二、入门
1. 步骤
-
1)新建student表
-
2)加入maven的mabatis和mysql依赖。为保证写在src/main/java下的sql映射文件能够被编译。需添加插件如下
-
<!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <build> <resources> <!--加载src/main/java文件下的配置文件,maven默认编译后不加载该目录下的非java文件--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
-
-
3)创建实体类,Student–保存表中一行数据
-
4)创建持久层dao接口,定义操作数据库的方法
-
5)创建mybatis的sql映射文件。
-
写在接口所在目录
-
文件名称和接口一致
-
<?xml version="1.0" encoding="UTF-8" ?> <!-- sql映射文件:写sql语句的 1.约束: <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> dtd格式文件约束, 2.约束文件作用:限制、检查在当前文件中出现的标签、属性必须符号mybatis要求 3.<mapper>:当前文件的根标签。必须的 4.namespace:命名空间,唯一值。可以是自定义字符串 要求使用dao接口的全限定名称 5.当前文件中,可以使用特定的标签,表示数据库的操作 <select>:查询,标签中写查询语句 <update>:更新 <insert>:插入 <delete>:删除 --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.zhangm.dao.StudentDao"> <!-- select:查询 id:要执行sql语句的唯一标识,mybatis会根据该id值执行sql语句。可以自定义,但是要求使用接口中的方法名。 resultType:表示结果类型,是sql语句执行后得到的ResultSet,遍历该ResultSet得到java对象的类型。 值写类型的全限定名称 --> <select id="selectStudents" resultType="cn.zhangm.domain.Student"> select * from student order by id </select> <!--插入--> <insert id="insertStudent"> insert into student values(#{id}, #{name}, #{email}, #{age}) </insert> </mapper>
-
-
6)创建mybatis的主配置文件。该文件提供了数据库连接信息和sql映射文件的位置信息
-
<?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> <!--settings:控制mybatis全局行为。--> <settings> <!--设置mybatis输出日志--> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!--环境配置,数据库的连接信息。default必须和某个<environment>的id一样,表示使用哪个环境--> <environments default="mydev"> <!-- 一个数据库信息的配置 id:一个唯一值,自定义,表示环境名称 <transactionManager>:mybatis事物类型 type:JDBC:表示jdbc中的connection对象的commit,rollback做事物处理 <dataSource>:表示数据源,连接数据库的 type:表示数据源类型,POOLED表示连接池 --> <environment id="mydev"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--sql mapper(sql映射文件)的位置--> <mappers> <!-- 一个mapper标签指定一个文件的位置。从类路径开始的路径信息 类路径:target / classes(类路径) --> <mapper resource="cn/zhangm/dao/StudentDao.xml"/> </mappers> </configuration>
-
-
7)创建使用mybatis类,访问数据库
-
//1.定义mybatis主配置文件名称,从类路径开始(target/classes) String config = "mybatis.xml"; //2.读取config配置文件 InputStream is = Resources.getResourceAsStream(config); //3.创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //4.创建sqlSessionFactory对象 SqlSessionFactory factory = builder.build(is); //5.(★)获取sqlSession对象 SqlSession sqlSession = factory.openSession(); //6.(★)指定执行sql语句的标识。sql映射文件的:namespace + . + 标签id String sqlId = "cn.zhangm.dao.StudentDao" + "." + "selectStudents"; //7.执行sql语句,通过sqlid List<Student> studentsList = sqlSession.selectList(sqlId); //8.输出 System.out.println(studentsList); //9.关闭sqlsession sqlSession.close();
-
2. 开启日志
-
在sql执行过程中,我们看不到sql执行详细过程,因此,来使用日志来帮助我们查看sql执行详情
-
做法:
-
在
mybatis.xml
文件中加入日志配置,可以在控制台输出执行的sql语句和参数 -
<settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>
-
3. 主要类介绍
- 1)Resources:mybatis中的类,读取核心配置文件
InputStream is = Resources.getResourceAsStream(config);
- 2)SqlSessionFactoryBuilder:创建SqlSessionFactory对象
new SqlSessionFactoryBuilder().build(is);
- 3)SqlSessionFactory:重量级对象,程序创建这个对象耗时长、耗费资源多。
- 在整个项目中有一个该对象就行了
- 它是一个接口。其实现类:
DefaultSqlSessionFactory
- 作用:获取SqlSession对象,
factory.openSession()
openSession()
方法说明- 无参:获取非自动提交事物的SqlSession对象
- openSession(boolean):若为true,则获取自动提交事物的对象。反之,获取非自动提交事物对象
- 4)SqlSession:接口,定义类操作数据库的方法(增删查改、事物操作…)
- 实现类:
DefaultSqlSession
- SqlSession线程不安全,需要在方法内部使用。执行sql语句后,需要关闭它。这样才能保证线程安全
- 实现类:
4. 工具类封装
-
package cn.zhangm.utils; 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; public class MybatisUtils { private static SqlSessionFactory factory; static { String config = "mybatis.xml";//mybatis核心配置文件 try { InputStream is = Resources.getResourceAsStream(config); factory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } } //获取SqlSession public static SqlSession getSqlSession(){ SqlSession sqlSession = null; if (factory != null) { System.out.println("------1"); sqlSession = factory.openSession();//非自动提交事物 } return sqlSession; } }
三、Dao代理
1. Dao代理
① 传统dao操作
-
1)传统dao操作为在impl包中定义类实现dao接口,该实现类实现sql语句的执行
-
public class StudentDaoImpl implements StudentDao { @Override public List<Student> selectStudents() { //1.获取sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); String sqlId = "cn.zhangm.dao.StudentDao.selectStudents"; //2.执行sql语句 List<Student> students = sqlSession.selectList(sqlId); //3.关闭资源 sqlSession.close(); return students; } }
-
-
2)数据查询的使用
-
@Test public void testSelectStudents(){ StudentDao dao = new StudentDaoImpl(); List<Student> students = dao.selectStudents(); for (Student student : students){ System.out.println(student); } }
-
② mybatis动态代理
-
1)实现动态代理的代码要求
namespace
必须是接口的全限定名称<select>
等标签的id必须是接口的方法名
-
2)获取实现类的方法
- 获取dao接口的实现类:
sqlSession.getMapper(接口.class);
- 获取dao接口的实现类:
-
3)动态代理原理
-
不用我们自己写dao接口的实现类了,通过getmapper方法,mybatis通过反射机制实现接口的实现类
-
/** * mybatis是如何通过动态反射创建接口的实体类的? * * StudentDao dao = new StudentDaoImpl(); * List<Student> students = dao.selectStudents();调用 * 1.dao对象,类型是StudentDao,其全限定名称:cn.zhangm.dao.StudentDao * 而全限定名称和namespace是一样的 * * 2.方法名称,selectStudents,这个方法名就是mapper文件的id值 * * 3.通过dao中方法的返回值,也可以确定mybatis要调用的方法 * 如果返回值是List,调用的是sqlSession的selectList方法 * 如果返回值是int、或非List,看mapper文件中的表示是<insert>、<update>就会调用响应的方法 * * 4.mybatis动态代理:mybatis根据dao的方法调用,获取执行sql语句的信息。 * mybatis根据dao接口,创建出一个dao接口的实现类,并创建这个对象。 * 完成sqlSession调用方法,访问数据库。 */
-
-
4)使用
-
@Test public void testSelectStudents(){ /** * 使用mybatis的动态代理机制,使用SqlSession的getMapper(dao接口) * getMapper能获取dao接口对应的实现类对象 */ SqlSession sqlSession = MybatisUtils.getSqlSession(); //★,实现类对应传统实现类体会他们的联系 StudentDao dao = sqlSession.getMapper(StudentDao.class); //调用dao的方法 List<Student> students = dao.selectStudents(); System.out.println(students); //sqlSession.close(); //动态代理自动释放资源 }
-
2.参数详解
2.1 parameterType
-
1)写在mapper文件中的一个属性,表示dao接口中方法参数的数据类型
-
例如
-
<select id="selectStudentById" parameterType="java.lang.Integer" resultType="cn.zhangm.domain.Student"> select * from student where id = #{id} </select>
-
-
2)parameterType他的值是java数据类型的全限定名称或者是mybatis定义的别名
- 例如:全限定名:
parameterType="java.lang.Integer"
。别名:parameterType="int"
- 其中,别名在mybatis官方文档可以查看,一般大写变小写,没有大写前面加 _
- 例如:全限定名:
-
3)注意:parameterType不是强制的,mybatis通过反射机制能够发现接口参数的数据类型。所以可以不写,一般也不写。
2.2 一个简单参数★
-
1)一个简单类型的参数:
-
简单类型:mybatis把 java的基本数据类型和string字符串 称为简单类型
-
在mapper文件获取简单类型的一个参数的值,使用
#{任意字符}
-
<select id="selectStudentById" resultType="cn.zhangm.domain.Student"> select * from student where id = #{id} </select>
-
-
2)原理
-
/** * 使用#{}之后,myabtis创建并执行PreparedStatement对象 * mybatis执行如下代码: * * 1.mybatis创建Connection、PreparedStatement对象: * String sql = "select * from student where id = ?" * PreparedStatement pst = conn.prepareStatement(sql); * pst.setInt(1, 1001) * * 2.执行sql封装为resultType="cn.zhangm.domain.Student"这个对象: * ResultSet rs = rs.executeQuery(); * Student student = null; * while(rs.next()){ * //从数据库取数一行数据,存到一个java对象属性中 * student = new Student(); * student.setId(rs.getInt("id")); * student.setName(rs.getString("name")); * student.setEmail(rs.getString("email")); * student.setAge(rs.getInt("age")); * } * * return student; //给了dao方法调用的返回值 * */
-
2.3 多个参数-@Param★
-
1)当Dao接口方法多个参数,需要通过名称使用参数。
-
在方法形参之前加入
@Param("自定义参数名")
,mapper文件使用#{自定义参数名}
获取。 -
例如
-
public List<Student> selectAll(@Param("myname") String name, @Param("myage") Integer age);
-
<select> select * from student where name = #{mynane} or age = #{myage} </select>
-
2.4 多个参数-对象★
-
1)使用java对象传递参数,java属性值就是sql需要的参数值。每一个属性就是一个参数。
-
2)语法格式:
#{属性名, javaType=类型名称,jdbcType=数据类型}
,很少用这种- javaType指java中的属性数据类型
- jdbcType指数据库中的数据类型
- 例如:
#{name,javaType=java.lang.String,jdbcType=VARCHAR}
-
3)简化语法(★)
#{属性名}
,(javaType,jdbcType的值mybatis反射能获取,不同我们提供)
-
4)例子
-
//接口方法 public List<Student> selectStudentByObject(Student student); //Student类,部分代码 public class Student { private Integer id; private String name; private String email; private Integer age; }
-
<select id="selectStudentByObject" resultType="cn.zhangm.domain.Student"> select * from student where name = #{name} or age = #{age} </select>
-
2.5 多个参数-按位置[了解]
- 1)参数位置从0开始,引用参数语法:
#{arg位置}
,第一个参数是#{arg0}
,第二个参数是#{arg1}
- 注意:mybatis-3.3版本之前使用
#{0}
方式,3.4之后使用#{arg0}
方式
- 注意:mybatis-3.3版本之前使用
2.6 多个参数-Map[了解]
- 1)Map集合可以存储多个值,使用Map向mapper文件一次传入多个参数。Map集合使用String类型作为key,Object类型作为value存储参数。mapper使用
#{key}
引用参数
2.7 #和$的区别★
- 1)
# 占位符
:告诉mybatis使用实际的参数值代替。并使用PreparedStatement对象执行sql语句,#{…}代替sql语句的"?",这样做更安全、迅速。通常也是使用这种方法。 - 2)
$ 字符串替换
:告诉mybatis使用" " 包 含 的 字 符 串 替 换 所 在 位 置 。 使 用 S t a t e m e n t 把 s q l 语 句 和 "包含的字符串替换所在位置。使用Statement把sql语句和 "包含的字符串替换所在位置。使用Statement把sql语句和{…}的内容连接起来。主要用在替换表名,列名等操作
3.封装输出结果
3.1 resultType
① 简介
-
1)
resultType
:执行sql得到ResultSet转换的类型,使用类型的完全限定名或别名。- 注意:如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身(如:List,resultType应该为Student的全限定名或别名)。resultType和resultMap不能同时使用。
-
2)处理方式:
-
mybatis执行sql语句,然后mybatis调用类的无参构造方法,创建对象。
-
mybatis把resultType指定列值付给同名的属性
-
例如:
-
<select id="selectStudentById" resultType="cn.zhangm.domain.Student"> select id,name,email,age from student </select>
-
对等的jdbc
-
ResultSet rs = executeQuery("select id,name,email,age from student"); while(rs.next()){ Student student = new Student(); student.setId(rs.getInt("id")); ... }
-
-
3)通过如上可以发现,mybatis通过mapper文件将查询结果封装为java对象,是基于java对象中的
setXxx()
方法。
② 简单类型
-
1)接口方法:
int countStudent();
-
2)mapper文件:
-
<select id="countStudent" resultType="int"> select count(*) from student </select>
-
-
3)reslutType的值:别名(查官方文档)、全限定名
③ 对象类型
见简介
④ Map类型
- 1)sql的查询结果作为Map的key和value。推荐使用
Map<Object, Object>
- 注意:Map作为接口的返回值,sql语句的查询结果最多只能有一条记录。大于一条记录就会报错
3.2 resultMap
-
1)resultMap自定义sql的结果和java对象属性的映射关系。更灵活的把值赋给指定的属性。
- 常用在列名和java对象属性名不一样的情况。
-
2)使用步骤
-
首先,定义resultMap标签
-
<!-- 定义resultMap id:自定义名称, type:java类型的全限定名称 主键列,使用id标签 column:列名 property:java类型的属性名 非主键列:result标签 --> <resultMap id="studentMap" type="cn.zhangm.domain.Student"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="email" property="email"/> <result column="age" property="age"/> </resultMap>
-
-
其次,写select标签,引用resultMap
-
<select id="selectAllStudents" resultMap="studentMap"> select * from student </select>
-
-
-
3)方式二:
-
<!-- resultMap的默认原则是:同名的列赋值给同名的属性 当列名和属性名不一致时,可以给列其别名,别名应和java类的属性名一致。 其作用与resultMap了功能一致,但是推荐使用resultMap的方式 --> <select id="selectAllStudents" resultMap="cn.zhangm.domain.MyStudent"> select id as stuid,name as stuname, email as stuemail, age as stuage from student </select>
-
3.3 别名
-
1)定义自定义类型的别名,在mybatis的核心配置文件中,使用
<typeAlias>
标签定义。 -
2)第一种方式,一次只能定义一个
-
<!-- 注意:该标签卸载seeings标签下面哦 --> <typeAliases> <typeAlias type="cn.zhangm.domain.Student" alias="Student"></typeAlias> </typeAliases>
-
type:自定义类型的全限定名称
-
alias:别名,短小精悍
-
-
3)第二种方式,package。
-
<typeAliases> <package name="cn.zhangm.domain" /> </typeAliases>
-
name:包名,这个包中的所有类,类名就是别名,不区分大小写
-
3.4 like查询
-
1)模糊查询实现的方式有两种,一是java代码给查询数据加上"%";二是
-
2)第一种方式:java代码的字符串加上%%,
String sql = "%xx%"
。推荐使用 -
3)第二种方式:在mapper文件中拼接
-
<select id="selectLikeTwo" resultType="cn.zhangm.domain.Student"> select * from student where name like "%" #{name} "%" </select>
-
四、动态SQL
1. 简介
- 1)动态sql:可以根据条件获得不同的sql语句,动态体现在where部分发生变化
- 2)动态sql的实现依赖mybatis的
<if>、<where>、<foreach>
标签
2. IF标签
-
1)对于
<if test="">
,当test为true时,会将其包含的sql片段拼接到其所在的sql语句中。-
接口
-
List<Student> selectStudentsIf(Student student);
-
-
mapper文件
-
<!-- if <if test="">,test中写的是java对象的属性值,对其判断 --> <select id="selectStudentsIf" resultType="cn.zhangm.domain.Student"> select * from student where 1=1 <if test="name != null and name !='' "> and name = #{name} </if> <if test="age > 0"> or age >= #{age} </if> </select>
-
-
测试方法
-
@Test public void testSIF(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); StudentDao mapper = sqlSession.getMapper(StudentDao.class); Student student = new Student(); student.setName("张三"); student.setAge(10); List<Student> students = mapper.selectStudentsIf(student); System.out.println(students); }
-
-
3. where标签
-
1)
<where>
标签在有查询条件时,会自动添加where子句;没有条件时不会添加。包含if标签,会去掉多余的and、or-
接口
-
List<Student> selectStudentsWhere(Student student);
-
-
mapper文件
-
<select id="selectStudentsWhere" resultType="cn.zhangm.domain.Student"> select * from student <where> <if test="name != null and name !='' "> and name = #{name} </if> <if test="age > 0"> or age >= #{age} </if> </where> </select>
-
-
测试代码
-
@Test public void testWhere(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); StudentDao mapper = sqlSession.getMapper(StudentDao.class); Student student = new Student(); student.setName("张三"); student.setAge(10); List<Student> students = mapper.selectStudentsWhere(student); System.out.println(students); }
-
-
4. foreach标签
-
1)
<foreach>
标签用于实现对数组与集合的遍历。需要注意的是:collection
:表示要遍历的集合类型,list、array等open、close、separator
为对遍历内容的sql拼接
-
2)语法
-
<foreach collcetion="集合类型" open="开始字符" close="结束字符" item="集合成员" separator="集合之间的分隔符"> #{item的值} </foreach>
-
-
3)情况一:collcetion为集合类型,
#{item}
获取每一次遍历的数据-
<select id="selectStudentsForeach" resultType="cn.zhangm.domain.Student"> select * from student where id in <foreach collection="list" item="myid" open="(" close=")" separator="," > #{myid} </foreach> </select>
-
-
4)情况二:collcetion为对象类型,
#{item.属性}
获取每一次遍历对象的属性-
<select id="selectStudentsForeachTwo" resultType="cn.zhangm.domain.Student"> select * from student where id in <foreach collection="list" item="stu" open="(" close=")" separator="," > #{stu.id} </foreach> </select>
-
5. 代码片段
-
1)
<sql>
标签用于定义SQL片段,以便其他sql标签复用。而其他标签使用该sql片段,需要使用<include>
子标签。 -
2)mapper文件
-
<sql id="studentSql"> select * from student </sql> <select id="selectStudentsSql" resultType="cn.zhangm.domain.Student"> <include refid="studentSql" /> where id = #{id} </select>
-
五、配置文件
1. 核心配置文件
-
<?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文件的位置,类路径根目录开始--> <properties resource="jdbc.properties" /> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <environments default="mydev"> <environment id="mydev"> <!-- transactionManager:mybatis提交事物、回滚事物的方式 type:事物的处理类型 1)JDBC:mybatis底层使用JDBC中的Connection对象的commit、rollback方法,处理事物 2)MANAGED:把mybatis的事物处理委托给其他容器(一个服务器软件,或者框架(spring)) --> <transactionManager type="JDBC"/> <!-- dataSource:表示数据源,java体系中规定实现了javax.sql.DataSource接口的都是数据源 dataSource表示Connection对象的 type:指定数据源的类型 1)POOLED:使用连接池,mybatis会创建javax.sql.DataSource接口的实现类PooleDataSource 2)UPOOLED:不使用连接池,每次执行sql语句,先创建连接,在关闭连接,myabtis创建UnPooleDataSource类 3)JNDI:java的命名和目录服务(类似windows注册表) --> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!--sql mapper(sql映射文件)的位置--> <mappers> <!-- 第一种方式:mapper标签指定一个文件 第二种方式:package标签指定一个目录下的所有文件 要求: 1.mapper文件名称需要和接口名称一样,区分大小写 2.mapper文件需要和接口在同一目录 --> <!--<mapper resource="cn/zhangm/dao/StudentDao.xml"/>--> <package name="cn.zhangm.dao" /> </mappers> </configuration>
2. 数据库属性配置
-
1)把数据库连接信息放到一个单独的文件中。和mybatis核心配置文件分开。
- 目的:便于修改、保存、处理多个数据库信息
-
2)步骤
- 在resources目录中定义一个
xxx.properties
文件。- 在该文件定义数据,格式为:key=value
- key一般使用"."做多级目录,例如:jdbc.mysql.driver=…
- 在mybatis的核心配置文件中,使用
<properties>
标签指定文件的位置。在需要使用值的地方使用${key}
- 在resources目录中定义一个
-
3)例如:
-
<!--指定properties文件的位置,类路径根目录开始--> <properties resource="jdbc.properties" /> <environments default="mydev"> <environment id="mydev"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>
-
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.user=root jdbc.password=root
-
六、扩展
1. PageHelper
-
1)PageHelper:做数据分页的。mybatis通用分页插件。支持13种数据库
-
2)使用步骤
-
maven依赖
-
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency>
-
-
加入plugin配置
-
<!--在<enviromenis>之前插入--> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor" /> </plugins>
-
-
pageHelper对象
-
@Test public void testPageHelper(){ //获取第1页,3条内容 PageHelper.startPage(1,3); ... }
-
-
operty name=“password” value="${jdbc.password}"/>
```
-
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.user=root jdbc.password=root
六、扩展
1. PageHelper
-
1)PageHelper:做数据分页的。mybatis通用分页插件。支持13种数据库
-
2)使用步骤
-
maven依赖
-
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency>
-
-
加入plugin配置
-
<!--在<enviromenis>之前插入--> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor" /> </plugins>
-
-
pageHelper对象
-
@Test public void testPageHelper(){ //获取第1页,3条内容 PageHelper.startPage(1,3); ... }
-
-