Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.cesgroup.mybatis;
import com.alibaba.fastjson.JSONObject;
import com.cesgroup.mybatis.entity.User;
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 org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class MybatisTest {
private SqlSession sqlSession=null;
private SqlSessionFactory sqlSessionFactory;
@Before
public void configMybatis() {
// 指定全局配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession
sqlSession = sqlSessionFactory.openSession(false);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSelectUser() {
User user = sqlSession.selectOne("MyMapper.selectUser", 1);
System.out.println(user);
sqlSession.close();
}
@Test
public void testInsertJsonObject() {
JSONObject userInfObject = new JSONObject();
userInfObject.put("address", "广东顺德");
userInfObject.put("email", "ceshi@cesgroup.com.cn");
Map userMap = new HashMap();
userMap.put("id", 20);
userMap.put("name", "测试");
userMap.put("info", userInfObject);
int num = sqlSession.insert("MyMapper.insert",userMap);
sqlSession.commit();
System.out.println("影响的行数:" + num);
}
}