从hibernate上理解mybatis

来源:互联网 发布:wamp5 无法启动apache 编辑:程序博客网 时间:2024/06/05 10:35

首先温习以下hibernate的结构:

hibernate.cfg.xml文件:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:sinosoft
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="myeclipse.connection.profile">
myoracle2
</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<mapping resource="com/sina/domain/Users.hbm.xml" />

</session-factory>


</hibernate-configuration>

User.java实体:

public class Users implements java.io.Serializable {


// Fields


private Long id;
private String name;
private String passwd;


// Constructors


/** default constructor */
public Users4() {
}


/** minimal constructor */
public Users4(Long id, String passwd) {
this.id = id;
this.passwd = passwd;
}


/** full constructor */
public Users4(Long id, String name, String passwd) {
this.id = id;
this.name = name;
this.passwd = passwd;
}


// Property accessors


public Long getId() {
return this.id;
}


public void setId(Long id) {
this.id = id;
}


public String getName() {
return this.name;
}


public void setName(String name) {
this.name = name;
}


public String getPasswd() {
return this.passwd;
}


public void setPasswd(String passwd) {
this.passwd = passwd;
}


}

对应的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.sina.domain.Users" table="USERS4" schema="SCOTT">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="64" unique="true" />
        </property>
        <property name="passwd" type="java.lang.String">
            <column name="PASSWD" length="64" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


上面时准备工作,对于如何通过hibernate对实体进行操作,看下面:

以验证是否合理为例:

Session session=null;
Transaction ts=null;
Users user=null;
try{
session=HibernateUtils.getCurrentSession();
ts=session.beginTransaction();
user=new Users();
List<Users> list=session.createQuery("from users where name="+user.getName()+"and passwd="+user.getPasswd()+"").list();
if(list.size()==1)
{
user=list.get(0);
}
else{
user=null;
}
ts.commit();

}catch(Exception e)
{
if(ts!=null)
{
ts.rollback();
}
throw new RuntimeException("wrong");
}finally
{
if(session!=null&&session.isOpen())
{
session.close();
}
}
return user;
}
}



那么我们来看看mybatis的:


mybatis的结构:

config.xml文件,相当于hibernate的hibernate.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">
   </properties>
     
   <!-- 类别名定义 -->  
   <typeAliases>  
   <!-- 
         <typeAlias type="com.mybatis.po.Student" alias="Student"/>
         <typeAlias type="com.mybatis.po.User" alias="User"/>   -->
         <package name="com.mybatis.po"/>
    </typeAliases>  
    <!-- 配置Mybatis的环境,事务及数据源等等 -->  
    <environments default="development">  
        <environment id="development">  
            <transactionManager type="JDBC" />  
            <dataSource type="POOLED">  
                <property name="driver" value="${jdbc.driver}" />  
                <property name="url" value="${jdbc.url}" />  
                <property name="username" value="${jdbc.username}" />  
                <property name="password" value="${jdbc.password}" />  
            </dataSource>  
        </environment>  
    </environments>  
      
    <!-- 指定映射文件或者映射类 -->  
    <mappers>
    <!--  
        <mapper resource="com/mybatis/persistence/StudentMapper.xml" />  
        <mapper resource="com/mybatis/persistence/UserMapper.xml" /> --> 
        <!-- 通过mapper接口加载映射文件 -->
        <!-- 映射单个 -->
        <!-- <mapper class="com.mybatis.persistence"/> -->
        <!-- 批量加载 -->
        <package name="com.mybatis.persistence"/>
    </mappers>  
</configuration> 


对于持久层框架而言,最终目的都是对实体数据库进行操作,而hibernate注重于实体类本身,把数据库表映射成对象,从每个实体类就有一个相应的xml文件中可以看出来

然而mybatis注重的是sql语句实体类的作用时接受执行sql语句返回的数据,关键在为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="com.mybatis.persistence.UserMapper">
<sql id="query_user_where">
<if test="userCustom.username!=null and userCustom.username!=''">
and username like '%${userCustom.username}%'
</if>
<if test="ids!=null">
<foreach collection="ids" item="user_id" open="and id in (" close=")" separator=",">
#{user_id}
</foreach>
</if>
</sql>
<resultMap type="user" id="userresultMap">
<id column="id" property="id"/>
<result column="username" property="username"/>
</resultMap>
<select id="findUserByresultMap" parameterType="int" resultMap="userresultMap">
select id,username from user where id=#{id}
</select>
<select id="getUserCount" parameterType="UserQueryVo" resultType="int">
select count(*) from user where user.sex=#{userCustom.sex} and user.username like '%${userCustom.username}%' 
</select>
<select id="findUserList" parameterType="UserQueryVo" resultType="UserCustom">
select id,username from user
<where>
<include refid="query_user_where"></include>
</where>
</select>
<select id="getUserById" parameterType="int" resultType="User">
select * from user where id = #{id}  
</select>
<select id="findUserByName" parameterType="java.lang.String" resultType="User">
select * from user where username like #{username}
</select>
<insert id="insertUser" parameterType="User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
<update id="updateUser" parameterType="User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
</mapper>

上面的代码可以看出,mybatis对每个sql语句进行封装,如指定输入输出类型


使用mybatis:

package com.mybatis.test;
import java.io.Reader;  
import java.util.ArrayList;
import java.util.List;


import org.apache.ibatis.io.Resources;  
import org.apache.ibatis.session.SqlSession;  
import org.apache.ibatis.session.SqlSessionFactory;  
import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
import org.junit.Before;  
import org.junit.Test;  
import com.mybatis.persistence.StudentMapper;  
import com.mybatis.persistence.UserMapper;
import com.mybatis.po.Student;  
import com.mybatis.po.User;
import com.mybatis.po.UserCustom;
import com.mybatis.po.UserQueryVo;
  
public class TestStudentMapper {  
  
    private SqlSession session=null;  
    @Before  
    public void setUp() throws Exception {  
        String resource = "config.xml";  
        Reader reader = Resources.getResourceAsReader(resource);  
        SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);  
        session = sqlMapper.openSession();  
    }  
      
    @Test
    public void testSelectUser(){
    UserMapper mapper=session.getMapper(UserMapper.class);
    UserQueryVo userQueryVo=new UserQueryVo();
    UserCustom userCustom=new UserCustom();
    userCustom.setId(2);
    userCustom.setUsername("aaa");
    List<Integer> ids=new ArrayList<Integer>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    userQueryVo.setIds(ids);
    userQueryVo.setUserCustom(userCustom);
    List<UserCustom> list=mapper.findUserList(userQueryVo);
    System.out.println(list.get(0).getUsername());
      

获得配置工厂,等等都跟hibernate思路一样。对于不懂的代码,自行百度吧,这里只是感受mybatis而已。

0 0
原创粉丝点击