package com.kaikeba.test;
import java.io.InputStream;
import java.util.Properties;
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.After;
import org.junit.Before;
import org.junit.Test;
import com.kaikeba.beans.Dept;
import com.kaikeba.dao.DeptMapper;
public class TestMain_01 {
private SqlSession session;
@Before
public void start() {
try {
InputStream inputStream = Resources.getResourceAsStream("myBatis-config.xml");
//切换环境
InputStream inputStream2 = Resources.getResourceAsStream("config2.properties");
Properties properties = new Properties();
properties.load(inputStream2);
// SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream, null, properties);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream, "development2");
this.session = factory.openSession();
}
catch (Exception exception) {
exception.printStackTrace();
}
}
@Test
public void test01() {
Dept dept = new Dept();
dept.setDname("风控部2");
dept.setLoc("北京");
try {
this.session.insert("Dept.saveDept", dept);
this.session.commit();
}
catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void test02() {
try {
Dept dept = this.session.selectOne("deptFindById", 1019);
System.out.println(dept.getDname());
}
catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void test03() {
try {
DeptMapper dao = this.session.getMapper(DeptMapper.class);
Dept dept = dao.deptFindById(1019);
System.out.println(dept.getDname());
}
catch (Exception e) {
e.printStackTrace();
}
}
@After
public void end() {
if (this.session != null) {
this.session.close();
}
}
}
<?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>
<properties resource="config.properties"> </properties>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.kaikeba.beans"/>
<!-- <typeAlias type="com.kaikeba.beans.Dept" alias="Dept"/> -->
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
<environment id="development2">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.kaikeba.dao"/>
</mappers>
</configuration>