前面我们讲了hibernate封装jdbc实现数据持久化,虽然使用hibernate可以生成SQL语句,甚至通过反向工程生成配置文件。但是在工作中,如果我们遇到一些复杂的SQL语句时,hibernate便显得无能为力。这时候,便要考虑使用mybatis.
MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。
用xml文件构建SqlSessionFactory实例是非常简单的事情。推荐在这个配置中使用类路径资源(classpath resource),但你可以使用任何Reader实例,包括用文件路径或file://开头的url创建的实例。MyBatis有一个实用类----Resources,它有很多方法,可以方便地从类路径及其它位置加载资源。
接下来,通过一个实例来讲解mybatis的使用吧!
1、创建web工程,添加如下jar包
2、创建配置文件
(1)数据库配置文件jdbc.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc\:oracle\:thin\:@localhost\:1521\:oracle
username=scott
password=tiger
(2)日志记录文件log4j.properties
# Global logging configuration
log4j.rootLogger=debug, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
(3)mybatis核心配置文件mybatis-config.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>
<properties resource="jdbc.properties"></properties>
<typeAliases >
<package name="org.lq.entity"/>
</typeAliases>
<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/entity/DeptDaoMapper.xml"/>
<mapper resource="org/lq/entity/EmpDaoMapper.xml"/>
</mappers>
</configuration>
(4)dept实体的配置文件DeptDaoMapper.xml
<?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.DeptDao">
<resultMap type="dept" id="deptdao">
<id property="deptno" column="deptno"/>
<result property="dname" column="dname"/>
<result property="loc" column="loc"/>
<collection property="emps" resultMap="empdao"></collection>
</resultMap>
<resultMap type="emp" id="empdao">
<id property="empno" column="empno"/>
<result property="ename" column="ename "/>
<result property="job" column="job"/>
<result property="mgr" column="mgr"/>
<result property="hiredate" column="hiredate"/>
<result property="sal" column="sal"/>
<result property="comm" column="comm"/>
</resultMap>
<select resultMap="deptdao" id="findAll" >
select * from dept d left join emp e on d.deptno=e.deptno
</select>
<select resultMap="deptdao" id="findbyId">
select * from dept where deptno=#{id}
</select>
<insert id="save" parameterType="dept" >
<selectKey keyProperty="deptno" order="BEFORE" resultType="int">
select deptno_seq.nextval from dual
</selectKey>
insert into dept (deptno,dname,loc) values(#{deptno},#{dname},#{loc})
</insert>
<update id="chg" parameterType="dept">
update dept set dname=#{dname},loc=#{loc} where deptno=#{deptno}
</update>
<delete id="del" >
delete from dept where deptno=#{id}
</delete>
</mapper>
(5)emp实体类的配置文件EmpDaoMapper.xml
<?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.EmpDao">
<resultMap type="emp" id="empdao">
<id property="empno" column="empno"/>
<result property="ename" column="ename "/>
<result property="job" column="job"/>
<result property="mgr" column="mgr"/>
<result property="hiredate" column="hiredate"/>
<result property="sal" column="sal"/>
<result property="comm" column="comm"/>
<result property="dept.deptno" column="deptno"/>
<result property="dept.dname" column="dname"/>
<result property="dept.loc" column="loc"/>
</resultMap>
<select id="findAll" resultMap="empdao">
select * from emp e left outer join dept d on(e.deptno=d.deptno)
</select>
</mapper>
3、创建实体类
(1)Dept.java
package org.lq.entity;
import java.util.List;
/**
* 部门
* @author zjc
* @date 2015-9-14
* @time 下午02:55:52
* @20150914_myBatis_t1
*/
public class Dept {
private int deptno;
private String dname;
private String loc;
private List<Emp> emps;
public Dept() {
super();
// TODO Auto-generated constructor stub
}
public Dept(int deptno, String dname, String loc) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = 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;
}
public void setLoc(String loc) {
this.loc = loc;
}
public List<Emp> getEmps() {
return emps;
}
public void setEmps(List<Emp> emps) {
this.emps = emps;
}
}
(2)Emp.java
package org.lq.entity;
import java.util.Date;
/**
* 员工
* @author zjc
* @date 2015-9-14
* @time 下午02:57:12
* @20150914_myBatis_t1
*/
public class Emp {
private int empno;
private String ename;
private String job;
private int mgr;
private Date hiredate;
private double sal;
private double comm;
private Dept dept;
public Emp() {
super();
// TODO Auto-generated constructor stub
}
public Emp(int empno, String ename, String job, int mgr, Date hiredate,
double sal, double comm, Dept dept) {
super();
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.dept = dept;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public double getComm() {
return comm;
}
public void setComm(double comm) {
this.comm = comm;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp [comm=" + comm + ", dept=" + dept + ", empno=" + empno
+ ", ename=" + ename + ", hiredate=" + hiredate + ", job="
+ job + ", mgr=" + mgr + ", sal=" + sal + "]";
}
}
4、创建模块接口
(1)部门模块DeptDao.java
package org.lq.dao;
import java.util.List;
import org.lq.entity.Dept;
import org.lq.entity.Emp;
public interface DeptDao {
public List<Dept> findAll();
public int save(Dept dept);
public int chg(Dept dept);
public Dept findbyId(int id);
public int del(int id);
}
(2)员工模块EmpDao.java
package org.lq.dao;
import java.util.List;
import org.lq.entity.Dept;
import org.lq.entity.Emp;
public interface EmpDao {
public List<Emp> findAll();
}
5、创建工具类BaseDao.java,用来开启和关闭session
package org.lq.utity;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* 工具类
* @author zjc
* @date 2015-9-14
* @time 下午02:42:55
* @20150914_myBatis_t1
*/
public class BaseDao {
private static SqlSessionFactory sf=null;
private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<SqlSession>();
static{
try {
Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
sf=new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getConn(){
SqlSession session=threadLocal.get();
if(session==null){
session=sf.openSession();
threadLocal.set(session);
}
return session;
}
public static void close(){
SqlSession session=threadLocal.get();
if(session!=null){
threadLocal.set(null);
session.close();
}
}
}
6、创建测试类Test.java
package org.lq.Test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.lq.dao.DeptDao;
import org.lq.dao.EmpDao;
import org.lq.entity.Dept;
import org.lq.entity.Emp;
import org.lq.utity.BaseDao;
/**
*
* @author zjc
* @date 2015-9-14
* @time 下午03:00:37
* @20150914_myBatis_t1
*/
public class Test {
SqlSession session= BaseDao.getConn();
EmpDao ed=session.getMapper(EmpDao.class);
DeptDao dd=session.getMapper(DeptDao.class);
/**
* 查询
*/
@org.junit.Test
public void e1(){
// DeptDao dd=session.getMapper(DeptDao.class);
// List<Dept> list=dd.findAll();
// for (Dept dept : list) {
// System.out.println(dept.getDname());
// }
List<Emp> list=ed.findAll();
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 根据id查询
*/
@org.junit.Test
public void e2(){
Dept dept=dd.findbyId(12);
System.out.println(dept.getDname());
}
/**
* 添加
*/
@org.junit.Test
public void e3(){
Dept dept=new Dept();
dept.setDname("李天");
dept.setLoc("伊朗");
int num=dd.save(dept);
session.commit();
System.out.println(num);
}
/**
* 修改
*/
@org.junit.Test
public void e4(){
Dept dept=dd.findbyId(12);
//dept.setDname("李天a");
dept.setLoc("伊拉克");
int num=dd.chg(dept);
session.commit();
System.out.println(num);
}
/**
* 删除
*/
@org.junit.Test
public void e5(){
int num=dd.del(12);
session.commit();
System.out.println(num);
}
}