Spring 整合 Hibernate

一、概述

  Spring整合Hibernate有什么好处?

  

其实都是ssh只是一个是struts2+spring3.0+hibernate,而另外一个是 springmvc+spring3.0+hibernate,纵向来看比较struts2和springmvc就可以了, 

首先说springMvc的优点
1,基于注解,stuts2虽然也有注解但是比较慢,没人用更多的时候是用xml的形式
2,能与spring其它技术整合比如说webflow等,
3,获取request及session对象比较简单,直接当参数值传入就行了,而struts2还需要通过ServletActionContext 对象获取
4,验证也比较简单,通过jsr-303就能实现,而不必写其它的代码,而struts2是通过写 actionName-validation.xml实现的
在说struts2的优点:
1,不必关注客户端是get提交还是set提交,springMvc的地址映射注解method是必须要被关注的
2,自动封装对象,springMvc,是封装在model里的只能在,所以会看到input框的数字类型有0或是0.0的选项
3,自定义结果类型,如xml什么的而springmvc确只能返回modelandView,或是不返回
4,将视图与结果解耦,因为struts2返回的是字符串,只有通过struts.xml才知道具体的是哪一个jsp,或是html,而springMvc只能明确的返回modelAndview
5,struts2 不需要专门的中文过滤器,而springMvc3需要配置
针对标签来说它们大同小异,但是当需要自动装配时 springMnc的form表单是必须使用的,而struts2则不用,其它功能上差不多,但效率上,springMvc的标签比struts2快因为,struts2通过request建立了堆和栈,所以效率上有所下降,我推荐还是用jsp自带标签不仅易于扩展而且,效率也不错
再说应用场景:如果都是成功之后跳一个页面的那两者都可以,而如果是其它的类型,那么struts2是一个不错的选择,举个例子来说Extjs4.0 增加对象自动装配struts2能实现,但springMvc就不行,除非你喜欢大量的request.getParamter()

二、整合步骤

  整合前准备:

  持久化类:

复制代码
@Entity
public class Book
{
    private Integer id;
    private String bookName;
    private String isbn;
    private int price;
    private int stock;
    public Integer getId()
    {
        return id;
    }
    public void setId(Integer id)
    {
        this.id = id;
    }
    public String getBookName()
    {
        return bookName;
    }
    public void setBookName(String bookName)
    {
        this.bookName = bookName;
    }
    public String getIsbn()
    {
        return isbn;
    }
    public void setIsbn(String isbn)
    {
        this.isbn = isbn;
    }
    public int getPrice()
    {
        return price;
    }
    public void setPrice(int price)
    {
        this.price = price;
    }
    public int getStock()
    {
        return stock;
    }
    public void setStock(int stock)
    {
        this.stock = stock;
    }
    public Book(Integer id, String bookName, String isbn, int price, int stock)
    {
        super();
        this.id = id;
        this.bookName = bookName;
        this.isbn = isbn;
        this.price = price;
        this.stock = stock;
    }
}
复制代码

  Dao层:

public interface BookDao
{
    public String findBookById(int id);
    
    public void saveBook(Book book);
}

  DaoImpl:

复制代码
@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);
    }
}
复制代码

  Service层:

public interface BookService
{
    public String findBookById(int id);
    public void saveBook(Book book);
}

  ServiceImpl:

复制代码
@Service
public class BookServiceImpl implements BookService
{
    @Autowired
    private BookDao bookDao;
    public String findBookById(int id)
    {
        return bookDao.findBookById(id);
    }
    public void saveBook(Book book)
    {
        bookDao.saveBook(book);
        
    }
}
复制代码
  1、加入Hibernate
  • 加入hibernate jar包
  • 添加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">
<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>
复制代码
  • 编写持久化类对应的.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>
复制代码
  2、加入Spring
  • 加入spring jar包
  • 加入Spring配置文件
复制代码
<?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>
复制代码
  3、编写测试类
复制代码
public class BookDaoImplTest
{
    private ApplicationContext context=null;
    private BookService bookService=null;
    
    {
         context= new ClassPathXmlApplicationContext("applicationContext.xml");  
         bookService=context.getBean(BookService.class);
    }
    @Test
    public void test()
    {
        DataSource dataSource=(DataSource) context.getBean(DataSource.class);
        System.out.println(dataSource);
    }
    @Test
    public void test2()
    {
        String bookName=bookService.findBookById(1);
        System.out.println(bookName);
    }
    
    @Test
    public void test3()
    {
        bookService.saveBook(new Book(2, "android源码分析", "1002", 45, 10));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值