pom.xml依賴導(dǎo)入
<!--測試-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
在resource下新建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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
創(chuàng)建pojo以對應(yīng)的xml文件,namespace可以自定義,id也可以自定義,但必須唯一,resultType定義結(jié)果類型
<?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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
使用junit測試
package com.qfedu.test;
import com.qfedu.pojo.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.Test;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
public class TestUser {
@Test
public void testGetAllUsers(){
/**
* 1. 使用mybatis的配置文件以及SqlSessionFactoryBuilder建造者模式創(chuàng)建SqlSessionFactory對象
* 2. 使用SqlSessionFactory對象的openSession()方法來得到一個SqlSession對象立膛,用該對象即可完成對象的所有的crud操作
* 3. 使用SqlSession對象來完成crud操作
* 4. 關(guān)閉資源
*
*/
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession();
/**
* session的crud方法("namespace.id");整個項目中的namespace.id必須唯一
*/
List<User> users = session.selectList("com.qfedu.pojo.UserMapper.selectUser");
for (User u : users) {
System.out.println(u);
}
if(session != null){
session.close();
session = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}