Spring与hibernate与mybatis

时间:2022-07-22
本文章向大家介绍Spring与hibernate与mybatis,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

众所周知,hibernate与mybatis都是项目开发中对持久层封装的工具,可以大大的提高开发的速度,但是他们有什么区别呢?

Hibernate是对JDBC进行了再次的轻量级的封装,建立对象与数据库表的映射,是一个全自动,面向对象的持久层框架。

mybatis是一个开源的关系对象映射框架,是一个半自动的持久层框架。

Mybatis:小巧、高效、简单、半自动化
Hibernate:高效、复杂、间接、全自动化

对比

Hibernate的真正掌握要比Mybatis来得难些。Mybatis框架相对简单很容易上手,但也相对简陋些。

一个项目中用到的复杂查询基本没有,就是简单的增删改查,这样选择hibernate效率就很快了,因为基本的sql语句已经被封装好了,根本不需要你去写sql语句,但是对于一个大型项目,复杂语句较多,选择mybatis就会加快许多,而且语句的管理也比较方便。

Hibernate的查询会将表中的所有字段查询出来,这一点会有性能消耗,当然如果自己写SQL就不会造成这样问题

是完整的对象/关系映射解决方案,它提供了对象状态管理的功能

Spring与Hibernate整合

  1. 创建与数据库相同的实体类pojo
  2. 创建Dao层的数据库操作类
@Repository
public class BookDaoImpl implements BookDao
{
    @Autowired
    private SessionFactory sessionFactory;
    
    //获取和当前线程绑定的Seesion
    private Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
    public String findBookById(int id)
    {
        String hql="SELECT bookName from Book where id=?";
        Query query=getSession().createQuery(hql).setInteger(0, id);
        String str= query.uniqueResult().toString();
        return str;
    }
    public void saveBook(Book book)
    {
        getSession().save(book);
    }
}

注意获得获取和当前线程绑定的Seesion

3.创建持久类对应的.hbm.xml文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-3-15 16:30:05 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.demo.ssm.po.Book" table="BOOK">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="bookName" type="java.lang.String">
            <column name="BOOK_NAME" />
        </property>
        <property name="isbn" type="java.lang.String">
            <column name="ISBN" />
        </property>
        <property name="price" type="int">
            <column name="PRICE" />
        </property>
        <property name="stock" type="int">
            <column name="STOCK" />
        </property>
    </class>
</hibernate-mapping>

映射数据库字段与pojo中的子段

以上三个步骤可以通过hibernate提供的代码自动生产工程自动生成。
  1. 创建Hibernate的配置文件
<?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">
<hibernate-configuration>
    <session-factory>
        <!-- 配置Hibernate的基本属性 -->
        <!-- 1.数据源配置到IOC容器中 -->
        <!-- 2.关联的.hbm.xml也在IOC容器配置SessionFactory实例 -->
        <!-- 3.配置Hibernate的基本属性:方言,SQL显示及格式化,生成数据表的策略以及二级缓存 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

2.在spring配置文件中整合hibernate

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <context:component-scan base-package="com.demo.ssm"></context:component-scan>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root"></property>
        <property name="password" value="281889"></property>
    </bean>  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
        <!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 -->
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <!-- //加载实体类的映射文件位置及名称 -->
        <property name="mappingLocations" value="classpath:com/demo/ssm/po/*.hbm.xml"></property>
    </bean>  
    
    <!-- 配置Spring声明式事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> 
    <!-- 配置事务事务属性 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切点,并把切点和事务属性关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.demo.ssm.daoImpl.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>

配置hibernate的sessionFactory,并添加数据源,添加实体类映射文件的位置,hibernate配置文件的位置。

Spring与Mybatis整合

spring整合mybatis,通过生成的代理对象来使用SqlSessionFactory创建SqlSession。或者将mapper交由spring进行管理。

  • 不使用原生dao整合
  1. 创建User类的接口,添加方法
public interface UserMapper {
    public User findUserById(String id);
}

2.创建mapper.xml文件,添加返回集,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.spy.mapper.UserMapper">
    
    <resultMap type="cn.spy.po.User" id="userMap">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sal" column="sal"/>
        <result property="sex" column="sex"/>
    </resultMap>
    <select id="findUserById" parameterType="string" resultMap="userMap">
        select * from users where id=#{id};
    </select>
</mapper>

3.创建sqlmapConfig.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>
    <mappers>
        <mapper resource="cn/spy/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

配置mapper.xml的位置

4.spring中整合mybatis

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!-- 加载数据库配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    
    <!-- 配置数据源 -->  
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
         <property name="driverClass" value="${jdbc.driverClass}"></property>  
                 <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>   
                 <property name="user" value="${jdbc.user}"></property>   
                 <property name="password" value="${jdbc.password}"></property>   
                 <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>  
                 <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>  
                 <property name="maxIdleTime" value="${jdbc.maxIdleTime}"></property> 
    </bean>     
    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis配置文件 -->
        <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- mapper配置 
        MapperFactoryBean:根据mapper接口生成代理对象
    -->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="cn.spy.mapper.UserMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
</beans>

这里需要配置sqlsessionfactory,配置mybatis配置文件位置,以及数据源

对于mapper的开发就没有dao层什么事情了,完全通过代理对象去查询结果。

当然上面的mapper.xml文件需要一个个添加配置很麻烦。

可以直接再Spring配置文件中添加mapper的扫描

<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的包名 :如果扫描多个包,每个包使用半角逗号分隔 -->
        <property name="basePackage" value="cn.spy.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

这种mapper批量被扫描,从mapper包中扫描出mapper接口。自动创建代理对象并且在spring容器中注册规则就是mapper.java和mapper.xml映射文件的名称需要保持一致,并且在一个包中。自动扫描出来的mapper的bean的id为mapper类名(首字母小写)。