1 package com.pt;
2
3 import java.io.Reader;
4 import java.util.Date;
5
6 import org.apache.ibatis.io.Resources;
7 import org.apache.ibatis.session.SqlSession;
8 import org.apache.ibatis.session.SqlSessionFactory;
9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 import org.junit.AfterClass;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13
14
15 public class TestUser {
16 //mybatis的配置文件
17 static String resource = "conf.xml";
18 //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
19 static Reader reader = null;
20 //构建sqlSession的工厂
21 static SqlSessionFactory sessionFactory = null;
22 //创建能执行映射文件中sql的sqlSession
23 static SqlSession session = null;
24 @BeforeClass
25 public static void setUp()throws Exception{
26 reader = Resources.getResourceAsReader(resource);
27 //构建sqlSession的工厂
28 sessionFactory = new SqlSessionFactoryBuilder().build(reader);
29 //创建能执行映射文件中sql的sqlSession
30 session = sessionFactory.openSession();
31 System.out.println("开始测试之前~~~~~~~~~"+ new Date());
32 }
33
34 @AfterClass
35 public static void tearDown(){
36 System.out.println("开始完成之后~~~~~~~~~"+ new Date());
37 }
38
39 @Test
40 public void testGet() throws Exception{
41
42 /**
43 * 映射sql的标识字符串,
44 * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
45 * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
46 */
47 String statement = "com.pt.map.UserMap.getUser";//映射sql的标识字符串
48 //执行查询返回一个唯一user对象的sql
49 int id = 1630002;
50 User user = session.selectOne(statement, id);
51 System.out.println(user.getUserId());
52 }
53
54 @Test
55 public void testAdd() throws Exception{
56 String statement = "com.pt.map.UserMap.addUser";//映射sql的标识字符串
57 //执行查询返回一个唯一user对象的sql
58 User newUser = new User();
59 int id = 1005000;
60 int insert_result = -88;
61 while(id++ != 1009000){
62 try{
63 newUser.setUserId(id);
64 insert_result = session.insert(statement, newUser);
65 session.commit();
66 System.out.println(id + "===INSERT SUCCESS===" + insert_result);
67 }catch(Exception e){
68 System.out.println(id + "===INSERT FAIL===" + insert_result);
69 e.printStackTrace();
70 }
71 Thread.sleep(0, 10);
72 }
73 }
74
75 }