ORM简介
对象关系映射。
ORM(Object Relational Mapping)框架采用元数据来描述对象一关系映射细节,元数据一般采用XML格式,并且存放在专门的对象一映射文件中。
只要提供了持久化类与表的映射关系,ORM框架在运行时就能参照映射文件的信息,把对象持久化到数据库中。当前ORM框架主要有五种:Hibernate(Nhibernate),iBATIS,mybatis,EclipseLink,JFinal。
ORM是通过使用描述对象和数据库之间映射的元数据,在我们想到描述的时候自然就想到了xml和特性(Attribute).目前的ORM框架中,Hibernate就是典型的使用xml文件作为描述实体对象的映射框架,而大名鼎鼎的Linq则是使用特性(Attribute)来描述的。
MyBatis
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis和Hibernate的不同:
MyBatis:半自动ORM框架、必须写SQL、事务处理、缓存都支持。
Hibernate:全自动ORM框架、可以不写SQL、事务处理、缓存都支持,二级缓存比mybatis更好。
案例使用动态代理实现简单的CRUD:
加依赖:
<dependencies>
<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.41</version>
</dependency>
</dependencies>
全局配置文件
mybatis-cfg.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="db.properties"/>
<!-- 自定义别名 -->
<typeAliases>
<typeAlias type="com.zsl.pojo.Emp" alias="emp"/>
</typeAliases>
<!-- 类型转换器 -->
<typeHandlers>
<typeHandler handler="com.zsl.typeHandler.ListtypeHandlers"/>
</typeHandlers>
<!-- 环境 -->
<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="EmpMapper.xml"/>
</mappers>
</configuration>
pojo
Emp
package com.zsl.pojo;
import java.util.List;
public class Emp {
private Integer empno;
private String ename;
private String job;
private List<String> pwd;
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer 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 List<String> getPwd() {
return pwd;
}
public void setPwd(List<String> pwd) {
this.pwd = pwd;
}
public Emp() {
super();
// TODO Auto-generated constructor stub
}
public Emp(Integer empno, String ename, String job, List<String> pwd) {
super();
this.empno = empno;
this.ename = ename;
this.job = job;
this.pwd = pwd;
}
@Override
public String toString() {
return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", pwd=" + pwd + "]";
}
}
映射文件
EmpMapper.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="com.zsl.dao.EmpMapper">
<insert id="addEmp" parameterType="emp">
insert into emp(ename,job,pwd)values(#{ename},#{job},#{pwd})
</insert>
<delete id="deleteEmpById" parameterType="int">
delete from emp where empno=#{empno}
</delete>
<update id="updateEmprById" parameterType="emp">
update emp set name = #{ename} where empno=#{empno}
</update>
<select id="getEmpById" parameterType="int" resultType="emp">
select empno,ename,job,pwd from emp where empno=#{empno}
</select>
</mapper>
通过SqlSessionFactory对象获取SQLSession对象
DbUtils
package com.zsl.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class DbUtils {
public static SqlSession getSession() throws IOException {
// TODO Auto-generated method stub
// 1.通过Resources对象加载配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-cfg.xml");
// 2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.通过SqlSessionFactory对象获取SQLSession对象
SqlSession session = factory.openSession();
return session;
}
public static void commit(SqlSession session) {
// TODO Auto-generated method stub
session.commit();
}
public static void close(SqlSession session) {
// TODO Auto-generated method stub
session.close();
}
}
Dao接口
package com.zsl.dao;
import java.io.IOException;
import com.zsl.pojo.Emp;
public interface EmpMapper {
public Integer addEmp(Emp emp) throws IOException;
public Integer deleteEmpById(Integer empno) throws IOException;
public Integer updateEmprById(Emp emp) throws IOException;
public Emp getEmpById(Integer empno) throws IOException;
}
Dao接口实现类
EmpMapperImpl
package com.zsl.dao.impl;
import java.io.IOException;
import com.zsl.dao.EmpMapper;
import com.zsl.pojo.Emp;
import com.zsl.utils.DbUtils;
public class EmpMapperImpl implements EmpMapper {
@Override
public Integer addEmp(Emp emp) throws IOException {
// TODO Auto-generated method stub
int insert = DbUtils.getSession().insert("com.zsl.dao.EmpMapper.addEmp",emp);
return insert;
}
@Override
public Integer deleteEmpById(Integer empno) throws IOException {
// TODO Auto-generated method stub
int delete = DbUtils.getSession().delete("com.zsl.dao.EmpMapper.deleteEmpById", empno);
return delete;
}
@Override
public Integer updateEmprById(Emp emp) throws IOException {
// TODO Auto-generated method stub
int update = DbUtils.getSession().update("com.zsl.dao.EmpMapper.updateEmprById", emp);
return update;
}
@Override
public Emp getEmpById(Integer empno) throws IOException {
// TODO Auto-generated method stub
Emp selectOne = DbUtils.getSession().selectOne("com.zsl.dao.EmpMapper.getEmpById", empno);
return selectOne;
}
}
测试
Test类里使用看动态代理,代理类是匿名内部类
public class Test {
public static void main(String[] args) throws IOException {
EmpMapper mapperImpl = new EmpMapperImpl();
EmpMapper empMapper = (EmpMapper) Proxy.newProxyInstance(EmpMapper.class.getClassLoader(), new Class[]{EmpMapper.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
String name = method.getName();
Object empno = null;
System.out.println(EmpMapper.class.getName()+"."+name);
for (Object object : args) {
System.out.println("参数:"+object);
empno = object;
}
//使用的不是目标方法,不是反射实现的目标方法。
//Object object =DbUtils.getSession().selectOne(EmpMapper.class.getName()+"."+name,empno);
Object object = method.invoke(mapperImpl, args); //实际执行的是接口实现类里的方法,具体查看动态代理源码分析
return object;
}
});
System.out.println(empMapper.getEmpById(7964));
}
}
原文地址:https://www.cnblogs.com/zhangsonglin/p/11172208.html