XML配置
- 导包
需要两个包,mybatis和jdbc驱动
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>6.0</version>
</dependency>
</dependencies>
- 核心配置文件(具体可看mybatis官网查看详细信息)
<?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"/>
<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/lq/mapper/DeptMapper.xml"/>
<mapper resource="org/lq/mapper/EmpMapper.xml"/>
</mappers>
</configuration>
- 创建实体类
- 创建dao
- 创建实体类对应的映射文件
<?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.lq.dao.DeptMapper">
//对应的resultMap,
<resultMap id="BaseResultMap" type="org.lq.model.Dept">
<id column="DEPTNO" jdbcType="DECIMAL" property="deptno" />
<result column="DNAME" jdbcType="VARCHAR" property="dname" />
<result column="LOC" jdbcType="VARCHAR" property="loc" />
</resultMap>
<sql id="Base_Column_List">
DEPTNO, DNAME, LOC
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from DEPT
where DEPTNO = #{deptno,jdbcType=DECIMAL}
</select>
</mapper>
- 测试
SqlSessionFactory build;
try {
build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
DeptMapper dao = build.openSession().getMapper(DeptMapper.class);
System.out.println(dao.selectByPrimaryKey(10L));
} catch (IOException e) {
e.printStackTrace();
}
注解配置
。。。。