MyBatis框架的使用(一)

时间:2022-08-13 05:11:27

Mybatis框架的使用(一)

使用mybatis的大致步骤:

建工程


导入jar包


建立三个包:domain,dao,test


创建mybatis的xml配置文件mybatis.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="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value=""/>
<property name="url" value=""/>
<property name="username" value=""/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="" />
</mappers>
</configuration>

在domain中创建模型层类例如:Student

  public class Student{
private String Name;
public void setName(String Name){
this.Name = Name;
}
}

创建相应的mapper映射器

映射器创建在dao包中。

public interface StudentMapper{
public Student findByName(String Name);
}

创建映射器配置文件

映射器配置文件应与映射器在同一目录下,建议与映射器同名.
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="com.dao.StudentMapper">
<select id="findByName" parameterType="String" resultType="com.domain.Student">
select * from student where Name=#{Name};
</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>
<enviroments default="development">
......
</enviroment>
<mappers>
<mapper resource="com/dao/StudentMapper.xml" />
</mappers>
</configuration>

创建测试类进行测试:

测试有两种方法:
- 使用Test注释进行测试
首先,为工程添加单元测试类库:
大致步骤:选中项目之后,右键点击Build Path ->Add Library->JUnit之后一直下一步。然后创建一个新的测试类用于测试:

public class TestStudent{
/*
在进行测试时,大致步骤如下:
1.读取配置文件.
2.创建SqlSessionFactory工厂.
3.获取mapper映射器.
4.调用mapper相应的方法,得到相应的结果.
5.提交事务(CRUD中除去查询外,均需要进行事务提交)
6.关闭sqlSession.
7.打印结束语句(用户判断是否结束测试,非必要的)
*/

@Test
public void Test() throw IOException{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
System.out.println(studentMapper.findByName("李某某"));
sqlSession.close();
System.out.println("END");

}
}

之后敲击shift+alt+X +T进行单元测试。
- 也可以通过写一个main方法进行测试
main方法内的代码与使用单元测试使用的代码是一样的。

public static void main(String args[]){
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
System.out.println(studentMapper.findByName("李某某"));
sqlSession.close();
System.out.println("END");
}