MyBatis单元测试

一.项目总体结构

二.用到jar包:

mybatis-3.4.1.jar

ojdbc14-10.2.0.3.0.jar

JUnit4

三.配置文件

1.test.properties
1 jdbc.utf-8.driver = oracle.jdbc.driver.OracleDriver
2 jdbc.utf-8.jdbcUrl = jdbc:oracle:thin:@xx.0.0.xxx:1521:orcl
3 jdbc.utf-8.username = txxx
4 jdbc.utf-8.password = txxx
2.mybatis.xml
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <environments default="development">
 7         <!-- 可以配置多个环境指向不同数据库,每个数据库可分别用一个SqlSessionFactory创建实例 -->
 8         <environment id="development">
 9             <!-- 这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务范围
10             <transactionManager type="JDBC" /> -->
11             <!-- 这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。
12              默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为 -->
13             <transactionManager type="MANAGED">
14                 <property name="closeConnection" value="false" />
15             </transactionManager>
16             <dataSource type="POOLED">
17                 <property name="driver" value="${jdbc.utf-8.driver}" />
18                 <property name="url" value="${jdbc.utf-8.jdbcUrl}" />
19                 <property name="username" value="${jdbc.utf-8.username}" />
20                 <property name="password" value="${jdbc.utf-8.password}" />
21             </dataSource>
22         </environment>
23     </environments>
24     <mappers>
25         <mapper resource="mappers/StuMapper.xml" />
26     </mappers>
27 </configuration>
3.StuMapper.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">
<!-- 如果自己写mapperDao的实现类,命名空间最好与实体对应 -->
<!-- <mapper namespace="entity.StuScore"> -->
<!-- 如果使用mybatis来自动生成mapper接口的实现类,命名空间应该与mapper接口对应 -->
<mapper namespace="dao.StuScoreDao">
    <!-- 实体映射 -->
    <resultMap type="entity.StuScore" id="StuMap">
        <result property="name" column="NAME"/>
        <result property="subject" column="SUBJECT"/>
        <result property="score" column="SCORE"/>
        <result property="stuid" column="STUID"/>
    </resultMap>
    <!--根据学号查询学生 -->
    <select id="selectByStuid" resultMap="StuMap">
        SELECT * FROM stuscore WHERE STUID = #{stuid}
    </select>
    
    <!-- 增加数据 -->
    <insert id="add" parameterType="entity.StuScore">
        INSERT INTO stuscore(
            NAME,
            SUBJECT,
            SCORE,
            STUID
        )VALUES(
            #{name},
            <!-- 对于允许为空的列要加上jdbcType -->
            #{subject,jdbcType=VARCHAR},
            #{score,jdbcType=NUMERIC},
            #{stuid} 
        )
    </insert>
    
    <!-- 删除数据  -->
    <delete id="delete" parameterType="int">
        DELETE FROM stuscore
        WHERE STUID = #{stuid}
    </delete>
    
    <!-- 更新数据 -->
    <update id="update" parameterType="entity.StuScore">
        UPDATE stuscore
        <set>
            <if test="name != null">NAME = #{name},</if>
            <if test="subject != null">SUBJECT = #{subject},</if>
            <if test="score != null">SCORE = #{score}</if>
        </set>
        WHERE STUID = #{stuid}
    </update>
</mapper>

四.java代码部分

1.实体类
 1 package entity;
 2 
 3 public class StuScore {
 4     //姓名
 5     private String name;
 6     //学科
 7     private String subject;
 8     //成绩
 9     private Integer Score;
10     //学号
11     private Integer stuid;
12     public StuScore() {
13         super();
14     }
15     public StuScore(String name, String subject, Integer score, Integer stuid) {
16         super();
17         this.name = name;
18         this.subject = subject;
19         Score = score;
20         this.stuid = stuid;
21     }
22     public String getName() {
23         return name;
24     }
25     public void setName(String name) {
26         this.name = name;
27     }
28     public String getSbuject() {
29         return subject;
30     }
31     public void setSbuject(String sbuject) {
32         this.subject = sbuject;
33     }
34     public Integer getScore() {
35         return Score;
36     }
37     public void setScore(Integer score) {
38         Score = score;
39     }
40     public Integer getStuid() {
41         return stuid;
42     }
43     public void setStuid(Integer stuid) {
44         this.stuid = stuid;
45     }
46 }
2.StuScoreDao
 1 package dao;
 2 
 3 import entity.StuScore;
 4 
 5 public interface StuScoreDao {
 6     /**
 7      * 根据学号查询学生
 8      * @param stuid
 9      * @return
10      */
11     public StuScore selectByStuid(Integer stuid);
12     
13     /**
14      * 增加学生
15      * @param stu
16      */
17     public void insertStu(StuScore stu);
18     
19     /**
20      * 根据stuid删除学生
21      * @param stu
22      */
23     public void deleteStu(Integer stuid);
24     
25     /**
26      * 更新学生数据
27      * @param stu
28      */
29     public void updateStu(StuScore stu);
30 }
3.不需要写StuScoreDao实现类的测试方法
 1 package test;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.Properties;
 6 
 7 import org.apache.ibatis.io.Resources;
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.apache.ibatis.session.SqlSessionFactory;
10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
11 import org.junit.After;
12 import org.junit.Before;
13 import org.junit.Test;
14 
15 import dao.StuScoreDao;
16 import entity.StuScore;
17 
18 public class TestMyBatisMapperDao {
19     private StuScoreDao mapper;
20     
21     @Before
22     public void setUp() throws Exception {
23         InputStream fis = null;
24         InputStream inputStream = null;
25         try {
26             //创建Properties对象
27             Properties prop = new Properties();
28             //创建输入流,指向配置文件,getResourceAsStream可以从classpath加载资源
29             fis= Resources.getResourceAsStream("test.properties");
30             //加载属性文件
31             prop.load(fis);
32             inputStream = Resources.getResourceAsStream("mybatis.xml");
33             //build的第二个参数对应mybatis.xml配置文件的<environment id="development">标签的id,
34             //其中后面两个参数可选,若第二个参数不写则默认为"development"
35             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"development",prop);
36             SqlSession sqlSession = sqlSessionFactory.openSession();
37             //StuScoreDao.class与配置文件StuMapper的namespace对应
38             mapper = sqlSession.getMapper(StuScoreDao.class);
39         } catch (IOException e) {
40             // TODO Auto-generated catch block
41             e.printStackTrace();
42         }finally{
43             if(fis != null){
44                 try {
45                     fis.close();
46                 } catch (IOException e) {
47                     // TODO Auto-generated catch block
48                     e.printStackTrace();
49                 }
50             }
51             if(inputStream != null){
52                 try {
53                     inputStream.close();
54                 } catch (IOException e) {
55                     // TODO Auto-generated catch block
56                     e.printStackTrace();
57                 }
58             }
59         }
60     }
61 
62     @After
63     public void tearDown() throws Exception {
64     }
65     
66     @Test
67     //根据学号查询学生
68     public void test1() {
69         StuScore stuScores = this.mapper.selectByStuid(2);
70         System.out.println(stuScores.getName());
71     }
72     
73     @Test
74     //增加学生
75     public void test2(){
76         StuScore stuScore = new StuScore();
77         stuScore.setName("测试");
78         stuScore.setStuid(9);
79         this.mapper.insertStu(stuScore);
80     }
81     
82     @Test
83     //删除
84     public void test3(){
85         this.mapper.deleteStu(9);
86     }
87     
88     @Test
89     //修改数据
90     public void test4(){
91         StuScore stu = new StuScore();
92         stu.setName("测试1");
93         stu.setStuid(9);
94         this.mapper.updateStu(stu);
95     }
96 }
4.实现类
 1 package dao.Impl;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.Properties;
 6 
 7 import org.apache.ibatis.io.Resources;
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 
11 import dao.StuScoreDao;
12 import entity.StuScore;
13 
14 public class StuScoreImpl implements StuScoreDao {
15     private static SqlSession sqlSession;
16     //如果有多个mapper文件,为防止混淆,可以使用NAMESPACE来取指定mapper文件中的sql,第一个方法selectByStuid()示例了用法
17     private static final String NAMESPACE = StuScore.class.getName();//即 entity.StuScore
18     static{
19         InputStream fis = null;
20         InputStream inputStream = null;
21         try {
22             //创建Properties对象
23             Properties prop = new Properties();
24             //创建输入流,指向配置文件,getResourceAsStream可以从classpath加载资源
25             fis= Resources.getResourceAsStream("test.properties");
26             //加载属性文件
27             prop.load(fis);
28             inputStream = Resources.getResourceAsStream("mybatis.xml");
29             //build的第二个参数对应mybatis.xml配置文件的<environment id="development">标签的id,
30             //其中后面两个参数可选,若第二个参数不写则默认为"development"
31             sqlSession = new SqlSessionFactoryBuilder().build(inputStream,"development",prop).openSession();
32         } catch (IOException e) {
33             // TODO Auto-generated catch block
34             e.printStackTrace();
35         }finally{
36             if(fis != null){
37                 try {
38                     fis.close();
39                 } catch (IOException e) {
40                     // TODO Auto-generated catch block
41                     e.printStackTrace();
42                 }
43             }
44             if(inputStream != null){
45                 try {
46                     inputStream.close();
47                 } catch (IOException e) {
48                     // TODO Auto-generated catch block
49                     e.printStackTrace();
50                 }
51             }
52         }
53     }
54     
55     /**
56      * 根据学号查询学生
57      * @param stuid
58      * @return
59      */
60     @Override
61     public StuScore selectByStuid(Integer stuid) {
62         // TODO Auto-generated method stub
63         //示例使用NAMESAPCE的用法
64         return sqlSession.selectOne(NAMESPACE+".selectByStuid",stuid);
65     }
66 
67     /**
68      * 增加学生
69      * @param stu
70      */
71     @Override
72     public void insertStu(StuScore stu) {
73         // TODO Auto-generated method stub
74         sqlSession.insert("add",stu);
75     }
76 
77     /**
78      * 根据stuid删除学生
79      * @param stu
80      */
81     @Override
82     public void deleteStu(Integer stuid) {
83         // TODO Auto-generated method stub
84         sqlSession.delete("delete",stuid);
85     }
86 
87     /**
88      * 更新学生数据
89      * @param stu
90      */
91     @Override
92     public void updateStu(StuScore stu) {
93         // TODO Auto-generated method stub
94         sqlSession.update("update", stu);
95     }
96 
97 }
5.自己写实现类的测试方法
 1 package test;
 2 
 3 import org.junit.After;
 4 import org.junit.Before;
 5 import org.junit.Test;
 6 
 7 import dao.StuScoreDao;
 8 import dao.Impl.StuScoreImpl;
 9 import entity.StuScore;
10 
11 public class TestMybatis {
12     
13     private StuScoreDao stuScoreDao;
14     
15     @Before
16     public void setUp() throws Exception {
17         this.stuScoreDao = new StuScoreImpl();
18     }
19 
20     @After
21     public void tearDown() throws Exception {
22     }
23 
24     @Test
25     //根据学号查询学生
26     public void test1() {
27         StuScore stuScores = this.stuScoreDao.selectByStuid(2);
28         System.out.println(stuScores.getName());
29     }
30     
31     @Test
32     //增加学生
33     public void test2(){
34         StuScore stuScore = new StuScore();
35         stuScore.setName("测试");
36         stuScore.setStuid(9);
37         this.stuScoreDao.insertStu(stuScore);
38     }
39     
40     @Test
41     //删除
42     public void test3(){
43         this.stuScoreDao.deleteStu(9);
44     }
45     
46     @Test
47     //修改数据
48     public void test4(){
49         StuScore stu = new StuScore();
50         stu.setName("测试1");
51         stu.setStuid(9);
52         this.stuScoreDao.updateStu(stu);
53     }
54 }

 

posted @ 2016-10-28 14:15  执迷而不悔  阅读(17346)  评论(0编辑  收藏  举报