1、导入依赖jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<build>
<!-- 主资源目录 -->
<resources>
<resource>
<!--<!– 设定主资源目录 –>-->
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<!-- 设定主资源目录 -->
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2、封装Route对象,此处省略
3、主配置文件sqlMapper.xml,应该放在main/resource目录下
<?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="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///数据库名?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="***"/>
<property name="password" value="***"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/sun/dao/RouteMapper.xml"/>
</mappers>
</configuration>
4、映射文件
<?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="com.sun.pojo.Route">
<select id="getById" resultType="com.sun.pojo.Route" parameterType="int">
select * from tab_route where rid = #{id}
</select>
</mapper>
5、测试代码
package com.sun.mapper;
import com.sun.pojo.Route;
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 java.io.IOException;
import java.io.InputStream;
public class RouteMapper {
public static void main(String[] args) throws IOException {
RouteMapper routeMapper = new RouteMapper();
Route byId = routeMapper.getById();
System.out.println(byId);
}
public Route getById() throws IOException {
//加载配置文件
String resource = "sqlMapper.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlsessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行statement
Route route = sqlSession.selectOne("com.sun.pojo.Route.getById",1);
return route;
}
}