MyBatis是一个基于Java的持久层框架,几乎可以代替JDBC,且同时提供接口编程;作为持久层框架,大家也很容易想到Hibernate框架;Hibernate和MyBatis都是ORM框架(对象关系映射框架:把POJO对象与数据库表相互映射的框架);
一、MyBatis与Hibernate
Hibernate代码示例:
-映射文件:
<hibernate-mapping>
<class name="cn.infocore.pojo.Role" table="t_role">
<id name="id" type="java.lang.Integer" column="t_id">
<generator class="identity"/>
</id>
<property name="name" column="t_name" type="string"/>
<property name="note" column="t_note" type="string"/>
</class>
</hibernate-mapping>
-通过session操作数据库数据:
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
...
session.save(role);
Role role=session.get(Role.class,1);
session.update(role);
session.delete(role);
整个过程中未看到任何SQL,是因为Hibernate会根据映射关系来生成对应的SQL,对于只注重逻辑不注重性能的项目开发很有优势,但现在的互联网时代,性能的需求越来越高,因此MyBatis成了持久层框架的首选;MyBatis不屏蔽SQL,这个的好处就是我们可以自己定制SQL规则,从而优化性能;
-映射文件:
<?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="cn.infocore.mybatis.RoleMapper">
<insert id="insertRole" useGeneratedKeys="true" keyProperty="id">
insert into t_role(t_name, t_note) values (#{name}, #{note})
</insert>
<delete id="deleteRole" parameterType="long">
delete from t_role where t_id=#{id}
</delete>
<select id="getRole" parameterType="long" resultType="role">
select t_id, t_name , t_note from t_role where t_id = #{id}
</select>
<update id="updateRole" parameterType="role">
update t_role set t_name = #{name},t_note = #{note} where t_id = #{id}
</update>
</mapper>
-定义接口:
public interface RoleMapper {
public int insertRole(Role role);
public Role getRole(@Param("id") Integer id);
public int updateRole(Role role);
public int deleteRole(@Param("id") Integer id);
}
-通过SqlSession操作数据库数据:
SqlSession session=MyBatisUtil.getSqlSession();
RoleMapper mapper=session.getMapper(RoleMapper.class);
...
mapper.insertRole(role);
Role role=mapper.getRole(id);
mapper.deleteRole(id);
mapper.updateRole(role);
-Hibernate:
优点:配置不需要编写大量SQL就可以完全映射,同时提供日志、缓存、级联(比MyBatis强大)等特性,提供HQL语言,使用起来非常方便;
缺点:当多表关联超过3个时,级联会造成太多性能丢失;且不支持动态关联(因为无法自定义SQL);不支持存储过程;性能低;
-MyBatis:
优点:自定义SQL,支持动态SQL,处理列表,动态生成表名、支持存储过程、可优化性高意味着性能高;
缺点:代码量大,支持的工具有限,基本需要手动编写;
因此对于性能要求不高的系统,如管理系统、ERP等推荐Hibernate;对于高性能、响应快、灵活的系统推荐MyBatis;