Spring整合Hibernate

本文介绍了一个使用Spring MVC和Hibernate技术的购书系统案例,详细展示了系统架构从导入jar包到测试代码的全过程,包括实体类定义、DAO层、Service层接口及其实现,同时还提供了实体类映射文件和Spring配置文件的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入jar包


2.实体类Book和UserAccount

public class Book {

	private String isbn;
	private String bookName;
	private float price;
	private int stock;
	public String getIsbn() {
		return isbn;
	}
	public int getStock() {
		return stock;
	}
	public void setStock(int stock) {
		this.stock = stock;
	}
	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
}
public class UserAccount {

	private int userId;
	private String username;
	private float account;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public float getAccount() {
		return account;
	}
	public void setAccount(float account) {
		this.account = account;
	}
}

3.Service层接口及实现类

public interface BookStoreService {

	public void purchase(int userId,String isbn);
}

@Service("bookStoreService")
public class BookStoreServiceImpl implements BookStoreService {

	@Autowired
	private BookStoreDao bookStoreDao;
	@Override
	public void purchase(int userId, String isbn) {
		//1.更新图书库存
		bookStoreDao.bookRemain(isbn);
		//2.更新用户账户
		bookStoreDao.userCountdel(isbn, userId);
		
	}

}

3.Dao层接口及实现类

public interface BookStoreDao {

	public float findPriceByIsbn(String isbn);
	
	public void userCountdel(String isbn,int userId);
	
	public void bookRemain(String isbn);
}

@Repository("bookStoreDao")
public class BookStoreDaoImpl implements BookStoreDao {

	@Autowired
	private SessionFactory sessionFactory;
	private Session getSession(){
		return  sessionFactory.getCurrentSession();
	}
	
	/**
	 * 根据书的编号更新图书的库存
	 */
	@Override
	public void bookRemain(String isbn) {
		/**
		 * 1.hql语句中表名是实体类的名字,并不是数据库表中的名称,通过*.hbm.xml文件将实体类映射到
		 * 数据库表;
		 * 2.对属性字段进行引用时,需要指明表名,否则返回结果为空。
		 */
		String hql = "SELECT b.stock FROM Book b WHERE b.isbn=?";
		Query query = getSession().createQuery(hql).setString(0, isbn);
		int remain = (Integer)query.uniqueResult();
		if(remain<1)
			throw new CountException("图书库存不足!");
		String hql2 = "UPDATE Book b SET b.stock = b.stock -1 WHERE b.isbn=?";
		query = getSession().createQuery(hql2).setString(0, isbn);
		query.executeUpdate();
		
	}

	/**
	 * 根据图书的编号获取图书的价格
	 */
	@Override
	public float findPriceByIsbn(String isbn) {
		String hql = "SELECT b.price FROM Book b WHERE b.isbn=?";
		Query query = getSession().createQuery(hql).setString(0, isbn);
		return (Float)query.uniqueResult();
	}

	/**
	 * 根据图书编号和用户id更新用户账户
	 */
	@Override
	public void userCountdel(String isbn ,int userId) {
		
		float price = findPriceByIsbn(isbn);
		String hql = "SELECT ua.account FROM UserAccount ua WHERE ua.userId=?";
		Query query = getSession().createQuery(hql).setInteger(0, userId);
		float account = (Float) query.uniqueResult();
		if(account<price)
			throw new CountException("用户余额不足!!");
		
		String hql2 = "UPDATE UserAccount ua SET ua.account=ua.account-"+price+" WHERE ua.userId=?";
		query = getSession().createQuery(hql2).setInteger(0, userId);
		query.executeUpdate();
		
		
	}

}

4.实体类映射文件(book.hbm.xml,UserAccount类似)

<?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">
<hibernate-mapping>
	<class name="com.neu.spring_hibernate.entities.Book" table="bookinfo">
		<id name="isbn" type="java.lang.String">
			<column name="isbn" />
			<generator class="native" />
		</id>
		<property name="bookName" type="java.lang.String">
			<column name="bookname"></column>
		</property>
		<property name="price" type="java.lang.Float">
			<column name="price"></column>
		</property>
		<property name="stock" type="java.lang.Integer">
			<column name="stock"></column>
		</property>

	</class>
</hibernate-mapping>

5.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
	">
	
	<context:property-placeholder location="classpath:jdbc.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>
	</bean>
	
	<context:component-scan base-package="com.neu.spring_hibernate.entities"></context:component-scan>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSource"></property>
	<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	<property name="mappingLocations" value="classpath:com/neu/spring_hibernate/entities/*.hbm.xml"></property>
	</bean>
	<!-- 配置事务管理器 -->
	<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 配置事务属性 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
	<tx:attributes>
		<tx:method name="get*" read-only="true"/>
		<tx:method name="*"/>
	</tx:attributes>
	</tx:advice>
	<!--配置切点,并将切点与事务联系起来  -->
	<aop:config>
		<aop:pointcut expression="execution(* com.neu.spring_hibernate.entities.*.*(..))" id="pointCut"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
	
	</aop:config>
</beans>

6.测试代码

public class BookStoreTest {

	ApplicationContext ctx = null;
	BookStoreService bookStoreService = null;
	{
		ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		bookStoreService = ctx.getBean(BookStoreService.class);
	}
	
	/**
	 * 测试数据源是否配置成功
	 * @throws SQLException
	 */
	@Test
	public void testDataSource() throws SQLException{
		DataSource dataSource = ctx.getBean(DataSource.class);
		System.out.println(dataSource.getConnection());
	}
	
	/**
	 * 测试purchase方法
	 */
	@Test
	public void testPurchase(){
		bookStoreService.purchase(1, "1001");
	}
}
注: 1.hql语句中表名是实体类的名字,并不是数据库表中的名称,通过*.hbm.xml文件将实体类映射到数据库表;
        2.对属性字段进行引用时,需要指明表名,否则返回结果为空。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值