Spring整合Hibernate

一 简述

Hibernate 上下文 Session 对象和 Spring 的事务管理合作的很好,并且hibernate是很好的orm框架,对于数据库查询不复杂的操作非常方便。

二 步骤

1 创建实体类

public class Book {



private Integer id;

private String bookName;

private String isbn;

private int price;

private int stock;

public Book(){}

public Book(String bookName, String isbn, int price, int stock) {

this.bookName = bookName;

this.isbn = isbn;

this.price = price;

this.stock = 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;

}



}

2 编写持久化类对应Book.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">



<hibernate-mapping>

    <class name="com.atguigu.spring.hibernate.entities.Book" table="SH_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>

3 创建IBookDao接口

public interface IBookDao {

public void saveBook(Book book);

public Book getBook(String bookName);

}

4 创建BookDaoImpl实现IBookDao

public class BookDaoImpl {

@Autowired

private SessionFactory sessionFactory;

//获取和当前线程绑定的 Session.

private Session getSession(){

return sessionFactory.getCurrentSession();

}

public void saveBook(Book book){

getSession().save(book);

}

public Book getBook(String bookName){

return (Book)getSession().createQuery("FROM Book b WHERE b.bookName=:bookName").setString("bookName", bookName).uniqueResult();

}

}

5 数据库配置文件配置db.properties

jdbc.user=root

jdbc.password=1230

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.jdbcUrl=jdbc:mysql:///spring7

jdbc.initPoolSize=5

jdbc.maxPoolSize=10

 

6 spring配置文件applicationContext.xml创建

<?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:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">



<!-- 配置自动扫描的包 -->

<context:component-scan base-package="com.atguigu.spring.hibernate"></context:component-scan>



<!-- 配置数据源 -->

<!-- 导入资源文件 -->

<context:property-placeholder location="classpath:db.properties"/>



<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="user" value="${jdbc.user}"></property>

<property name="password" value="${jdbc.password}"></property>

<property name="driverClass" value="${jdbc.driverClass}"></property>

<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>



<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>

<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>

</bean>



<!-- 配置 Hibernate 的 SessionFactory 实例: 通过 Spring 提供的 LocalSessionFactoryBean 进行配置 -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<!-- 配置数据源属性 -->

<property name="dataSource" ref="dataSource"></property>

<!-- 配置 hibernate 配置文件的位置及名称 -->

<!--  

<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

-->

<!-- 使用 hibernateProperties 属相来配置 Hibernate 原生的属性 -->

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.format_sql">true</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>

</props>

</property>

<!-- 配置 hibernate 映射文件的位置及名称, 可以使用通配符 -->

<property name="mappingLocations" 

value="classpath:com/spring/hibernate/entities/*.hbm.xml"></property>

</bean>



<!-- 配置 Spring 的声明式事务 -->

<!-- 1. 配置事务管理器 -->

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>



<!-- 2. 配置事务属性, 需要事务管理器 -->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="get*" read-only="true"/>

<tx:method name="purchase" propagation="REQUIRES_NEW"/>

<tx:method name="*"/>

</tx:attributes>

</tx:advice>



<!-- 3. 配置事务切点, 并把切点和事务属性关联起来 -->

<aop:config>

<aop:pointcut expression="execution(* com.spring.hibernate.service.*.*(..))" 

id="txPointcut"/>

<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>

</aop:config>



</beans>

7 测试类编写

public class SpringHibernateTest {



private ApplicationContext ctx = null;

private IBookDao bookDao = null;



{

ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

bookDao = ctx.getBean(IBookDao .class);

}

@Test

public void testSaveBook(){

bookDao.saveBook(new Book("书名", "sdfd324", 32, 1));

}

@Test

public void testGetBook(){

Book book=bookDao.getBook("书名");

}



}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流光影下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值