一、创建映射文件
要求
- 在dao包中创建文件StudentDao.xml
Mybatis框架----->(2)详解映射文件和配置文件 - 要求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">
<mapper namespace="com.StudentDao">
<select id="selectStudens" resultType="Student">
select * from student order by id
</select>
<!--插入操作-->
<insert id="insertStudent">
insert into student values (#{id},#{name},#{email},#{age})
</insert>
</mapper>
- 解析里面的参数:
- namespace值:
推荐使用dao接口的全限定名称,这里为 com.hcz.dao.StudentDao
- select标签:
表示查询操作;除此之外
update标签表示更新数据库的操作;
insert标签表示插入操作;
delete标签表示删除操作
- id值:
表示要执行的SQL语句的唯一标识,mybatis会使用这个id的值来找到要执行的SQL语句,可以自定义,但是要求你使用dao接口中的方法名称,这里查询的接口方法名称为selectStudens
- resultType值:
表示结果类型,是SQL语句执行后得到ResultSet,遍历这个ResultSet得到Java对象类型,它的值要使用全限定名称,这里为com.hcz.dao.Student
- 近似jdbc中的代码
<select id="selectStudens" resultType="Student">
select id,name from student
</select>
近似等价于以下jdbc代码
//执行查询,创建记录集
rs = st.executeQuery("select * from text ");
while (rs.next()){
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
//从数据库取出的数据转为Student对象,封装到List集合中
stuList.add(stu);
}
二、创建配置文件
<?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>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<!--配置mybatis环境:数据库的连接信息-->
<environments default="mysql">
<!--id:数据源的名称-->
<environment id="mysql">
<!--配置事务类型:使用jdbc事务(使用Connection的提交和回滚)-->
<transactionManager type="JDBC"/>
<!--数据源dataSource:创建数据库Connection对象的commit,rollback做事务处理
type:POOLED使用数据库的连接池
-->
<dataSource type="POOLED">
<!--连接池四要数-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3366/ssm?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hcz/dao/StudentDao.xml"/>
</mappers>
</configuration>
解析里面的标签属性:
- 1、< settings >标签
mybatis.xml 文件加入日志配置,可以在控制台输出执行的 sql 语句和参数
- 2、< transactionManager >标签
mybatis提交事务,回滚事务的方式
type属性:事务处理的类型
1)JDBC:表示mybatis底层是调用JDBC中的Connection对象的,然后提交事务commit和回滚事务rollback
2)MANAGED:把mybatis的事务处理委托给其他的容器(spring容器等)
- 3、< dataSource >标签
表示数据源,创建数据库Connection对象的commit,rollback做事务处理
type属性:使用数据源类型
1)POOLED:使用数据库的连接池,mybatis会创建 PooledDateSource类
2)UPOOLED:不使用连接池,在每次执行SQL语句,先创建连接,再执行sql,再关闭连接mybatis会创建UnPooledDateSource类
- 4、使用数据库属性配置文件
为了方便对数据库连接的管理,数据库连接四要素数据一般都是存放在一个专门的属性文件中的。目的是便于修改,保存,处理多个数据库的信息。下面给出具体的配置步骤:
步骤:
(1)在 classpath 路径下,创建 properties 文件
在 resources 目录创建一个属性配置文件, xxxx.properties ,格式是 key=value ,例如 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3366/ssm?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
(2)在mybatis的主配置文件,使用指定文件的位置
<!--指定properties文件的位置,从类路径根(/resource)开始找文件-->
<properties resource="jdbc.properties"/>
(3)使用 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}"/>
- 5、< mappers >标签映射器:映射文件的位置
(1)第一种方式:< mapper resource=" " />
一次只能找一个映射文件,使用相对于类路径的资源,从 classpath 路径查找文件,例如:
(2)第二种方式:< package name=""/> ,
使用包名,这个包中的所有xml文件都可以一次性找到,例如:
注意:
1.映射文件名称需要和接口名称一样,区分大小写
2.映射文件和dao接口需要在同一个目录下
三、创建测试类
public class MyTest {
public static void main(String[] args) {
//访问mybatis读取student数据
try {
//1.定义mybatis主配置文件,从类路径的根开始(target/classes)
String config = "mybatis.xml";
//2.读取配置文件,Resources: mybatis中的一个类, 负责读取主配置文件
InputStream in = Resources.getResourceAsStream(config );
//3.创建SqlSessionFactoryBuilder对象 : 创建SqlSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//4.创建SqlSessionFactory对象
SqlSessionFactory factory = builder.build(in);
//5.获取SqlSession对象,从SqlSessionFactory中获取SqlSession
/**
* 1. openSession() :无参数的, 获取是非自动提交事务的SqlSession对象
* 2. openSession(boolean): openSession(true) 获取自动提交事务的SqlSession.
* openSession(false) 非自动提交事务的SqlSession对象
*
*/
SqlSession sqlSession = factory.openSession();
/**
* SqlSession接口 :定义了操作数据的方法 例如 selectOne() ,selectList() ,
* insert(),update(), delete(), commit(), rollback()
*/
//6.【重要】指定要执行的SQL语句的标识,sql映射文件中的namespace+"."+标签的id值
String sqlId = "com.hcz.dao.StudentDao"+"."+"selectStudens";
//7.【重要】执行SQL语句,通过sqlId找到语句
List<Student> studentList = sqlSession.selectList(sqlId);
//8.输出结果
//studentList.forEach(student -> System.out.println(student));
for (Student student:studentList){
System.out.println(student);
}
//9.关闭连接
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 等价代码
//6.【重要】指定要执行的SQL语句的标识,sql映射文件中的namespace+"."+标签的id值
String sqlId = "com.hcz.dao.StudentDao"+"."+"selectStudens";
//7.【重要】执行SQL语句,通过sqlId找到语句
List<Student> studentList = sqlSession.selectList(sqlId);
近似等价于jdbc代码
Connection conn = 获取连接对象
String sql=” select id,name,email,age from student”
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();