定义bean,对应数据库中的表
package com.atChina.bean;
public class Employee {
private Integer deptno;
private String dname;
private String loc;
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
@Override
public String toString() {
return "Employee [deptno=" + deptno + ", dname=" + dname + ", loc="
+ loc + "]";
}
public void setLoc(String loc) {
this.loc = loc;
}
}
定义接口类
package com.atChina.dao;
import com.atChina.bean.Employee;
public interface EmployeeMapper {
public Employee getEmployeeById(Integer depno);
}
sql映射文件(EmployeeMapper.xml):sql映射文件的namespace,id要与接口类保持一致.
SqlSession和Connection一样都是非线程安全。
<?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">
<!-- namespace不能随便自定义了,应该是接口类的全限定名 -->
<mapper namespace="com.atChina.dao.EmployeeMapper">
<!-- id:唯一标识 ,应该是接口类中的抽象方法名
resultType: 返回值类型
#{deptno}:参数 -->
<select
id="getEmployeeById"
resultType="com.atChina.bean.Employee">
select * from DEPTTEST where deptno = #{deptno}
</select>
</mapper>
全局配置文件
<?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="oracle.jdbc.OracleDriver" />
<property
name="url"
value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property
name="username"
value="scott" />
<property
name="password"
value="123456" />
</dataSource>
</environment>
</environments>
<!-- 把sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
<mappers>
<mapper resource="EmployeeMapper.xml" />
</mappers>
</configuration>
执行sql,测试代码:
@Test
public void test2() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
try{
// 命名空间.id,这样别的配置文件里有同名的id,程序也不报错
EmployeeMapper em = openSession.getMapper(EmployeeMapper.class);
// 会为接口自动创建一个代理对象,代理对象去执行增删改查方法
System.out.println(em.getClass()); // 动态代理类
Employee ee = em.getEmployeeById(10);
System.out.println(ee);
}finally{
// 关闭
openSession.close();
}
}