Spring整合Hibernate

整合SpringMVC、Hibernate框架,以注解的方式实现作业三的各个功能。提示:应包含1个Cake实体类,1个CakeController控制器类,1个CakeService类,1个CakeDao类cakeForm.jsp、list.jsp2个页面,注意配置事务。

Cake.java:

package com.lrf.cakeonline.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="cake")
public class Cake {

	private int id;
	private int weight;
	private double price;
	private String pic;

	@Id
	@GeneratedValue(generator="my_inc")
	@GenericGenerator(name="my_inc",strategy="native")
	public int getId() {
		return id;
	}

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

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getPic() {
		return pic;
	}

	public void setPic(String pic) {
		this.pic = pic;
	}

	public Cake() {
		super();
	}

	public Cake(int id, int weight, double price, String pic) {
		super();
		this.id = id;
		this.weight = weight;
		this.price = price;
		this.pic = pic;
	}

	@Override
	public String toString() {
		return "Cake [id=" + id + ", weight=" + weight + ", price=" + price + ", pic=" + pic + "]";
	}

}

CakeDao.java:

package com.lrf.cakeonline.cake.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import com.lrf.cakeonline.entity.Cake;

@Repository
public class CakeDao {

	@Resource
	private SessionFactory sessionFactory;

	public void saveCake(Cake cake) {
		Session session = this.sessionFactory.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		session.save(cake);
		transaction.commit();
	}

	public List<Cake> findAllCakes() {
		Query query = this.sessionFactory.getCurrentSession().createQuery("from Cake");
		List<Cake> cakes = query.list();
		return cakes;
	}

	public Cake findCakeById(int cakeId) {
		Cake cake = (Cake) this.sessionFactory.getCurrentSession().get(Cake.class, cakeId);
		return cake;
	}

	public void editCake(Cake cake) {
		Session session = this.sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.update(cake);
		transaction.commit();
	}

	public void deleteCakeById(int cakeId) {
		Session session = this.sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		Cake cake = session.get(Cake.class, cakeId);
		session.delete(cake);
		transaction.commit();
	}
}

CakeService.java:

package com.lrf.cakeonline.cake.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lrf.cakeonline.cake.dao.CakeDao;
import com.lrf.cakeonline.entity.Cake;

@Service
@Transactional(readOnly = false)
public class CakeService {

	@Resource
	private CakeDao cakeDao;

	public void addCake(Cake cake) {
		this.cakeDao.saveCake(cake);
	}

	public void updateCake(Cake cake) {
		this.cakeDao.editCake(cake);
	}

	public void deleteCake(int cakeId) {
		this.cakeDao.deleteCakeById(cakeId);
	}

	@Transactional(readOnly = true)
	public List<Cake> findAll() {
		return this.cakeDao.findAllCakes();
	}

	@Transactional(readOnly = true)
	public Cake getCakeById(int cakeId) {
		return this.cakeDao.findCakeById(cakeId);
	}
}

CakeController.java:

package com.lrf.cakeonline.cake.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.lrf.cakeonline.cake.service.CakeService;
import com.lrf.cakeonline.entity.Cake;

@Controller
@RequestMapping("/cake")
public class CakeController {

	@Resource
	private CakeService cakeService;

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String toAdd(HttpServletRequest request) {
		request.setAttribute("action", "add");
		return "cakeForm";
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add(@RequestParam("upFile") MultipartFile file, Cake cake, HttpServletRequest request) {
		if (!file.getOriginalFilename().isEmpty()) {
			// 保存图片
			String path = request.getServletContext().getRealPath("/");
			try {
				FileCopyUtils.copy(file.getBytes(), new File(path + "/upload", file.getOriginalFilename()));
				cake.setPic(file.getOriginalFilename());
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 保存蛋糕信息
			this.cakeService.addCake(cake);
			System.out.println("add:" + cake);
			return "redirect:/cake/list";
		} else {
			request.setAttribute("error", "您还未选择图片!");
			request.setAttribute("action", "add");
			return "cakeForm";
		}
	}

	@RequestMapping("list")
	public String list(HttpServletRequest request) {
		List<Cake> cakeList = this.cakeService.findAll();
		request.setAttribute("cakes", cakeList);
		System.out.println("cakeList:" + cakeList);
		return "list";
	}

	@RequestMapping(value = "edit/{cakeId}", method = RequestMethod.GET)
	public String toEdit(@PathVariable("cakeId") int cakeId, HttpServletRequest request) {
		Cake cake = this.cakeService.getCakeById(cakeId);
		System.out.println("toEdit:" + cake);
		request.setAttribute("cake", cake);
		request.setAttribute("action", "edit");
		return "cakeForm";
	}

	@RequestMapping(value = "edit", method = RequestMethod.POST)
	public String editCake(@RequestParam("upFile") MultipartFile file, Cake cake, HttpServletRequest request) {
		System.out.println("editCake_before:" + cake);
		// 修改图片
		String path = request.getServletContext().getRealPath("/");
		try {
			if (!file.getOriginalFilename().isEmpty()) {
				FileCopyUtils.copy(file.getBytes(), new File(path + "/upload", file.getOriginalFilename()));
				cake.setPic(file.getOriginalFilename());
			} else {
				Cake oldCake = this.cakeService.getCakeById(cake.getId());
				cake.setPic(oldCake.getPic());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 修改蛋糕信息
		this.cakeService.updateCake(cake);
		System.out.println("editCake_after:" + cake);
		return "redirect:/cake/list";
	}

	@RequestMapping("/delete/{cakeId}")
	public String deleteCake(@PathVariable("cakeId") int cakeId) {
		this.cakeService.deleteCake(cakeId);
		System.out.println("deleteCake:" + cakeId);
		return "redirect:/cake/list";
	}
}

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<jsp:forward page="cake/list"></jsp:forward>
</body>
</html>

list.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="ctx" value="${pageContext.request.contextPath }" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="/Homework04/cake/add">新 增 蛋 糕</a><br><br>
	<table border="1">
		<tr>
			<th width="80px" style="text-align: center;">编 号</th>
			<th width="80px" style="text-align: center;">重 量</th>
			<th width="120px" style="text-align: center;">价 格</th>
			<th width="120px" style="text-align: center;">图 片</th>
			<th width="120px" style="text-align: center;">操 作</th>
		</tr>
		<c:forEach items="${cakes }" var="cake">
			<tr>
				<td style="text-align: center;">${cake.id }</td>
				<td style="text-align: center;">${cake.weight }</td>
				<td style="text-align: center;">${cake.price }</td>
				<td style="text-align: center;"><img alt="" src="${ctx }/upload/${cake.pic }" style="width:100px;height:100px;"></td>
				<td style="text-align: center;">
					<a href="/Homework04/cake/edit/${cake.id }">修 改</a><br/><br/>
					<a href="/Homework04/cake/delete/${cake.id }">删 除</a>
				</td>
			</tr>	
		</c:forEach>
	</table>
</body>
</html>

cakeForm.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:if test="${action == 'add' }">
		<h2>添加蛋糕</h2>
		<form action="/Homework04/cake/add" method="post" enctype="multipart/form-data">
			重 量:<input type="text" name="weight" value="${cake.weight }"/><br/>
			价 格:<input type="text" name="price" value="${cake.price }"/><br/>
			图 片:<input type="file" name="upFile" value="${cake.pic }"/><br/>
			<input type="submit" value="save"/><br/>
			<p style="color:red;">${error }</p>
		</form>
	</c:if>
	
	<c:if test="${action == 'edit' }">
		<h2>修改蛋糕</h2>
		<form action="/Homework04/cake/edit" method="post" enctype="multipart/form-data">
			<input type="hidden" name="id" value="${cake.id }"/>
			重 量:<input type="text" name="weight" value="${cake.weight }"/><br/>
			价 格:<input type="text" name="price" value="${cake.price }"/><br/>
			图 片:<input type="file" name="upFile" value="${cake.pic }"/><br/>
			<input type="submit" value="save"/>
		</form>
	</c:if>
</body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	
	<display-name>Homework4</display-name>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
            classpath*:/applicationContext.xml
        </param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<filter>
		<filter-name>openSessionInView</filter-name>
		<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>openSessionInView</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<mvc:annotation-driven />
	
	<!-- 处理静态资源 -->
	<mvc:default-servlet-handler/>
	
	<!-- 自动扫描且只扫描@Controller -->
	<context:component-scan base-package="com.lrf.cakeonline">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!-- 配置文件上传解析器(基于Commons FileUpload的文件上传) -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"></property><!-- 配置默认的字符集编码 -->
	</bean>
	
	<!-- 定义JSP文件的位置 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
	<description>Spring公共配置 </description>

	<!-- 配置Spring上下文的注解 -->
	<context:annotation-config />
	<!-- 使用annotation 自动注册bean, 并保证@Required@Autowired的属性被注入 -->
	<context:component-scan base-package="com.lrf.cakeonline">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 属性文件位置 -->
	<context:property-placeholder location="classpath:*.properties" />
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 要扫描的实体类所在的包 -->
		<property name="packagesToScan" value="com.lrf.cakeonline.entity" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.useUnicode">${hibernate.useUnicode}</prop>
				<prop key="hibernate.characterEncoding">${hibernate.characterEncoding}</prop>
				<prop key="current_session_context_class">thread</prop>
			</props>
		</property>
	</bean>
	
	<!-- 使用annotation定义事务,事务管理器配置, Hibernate单数据源事务 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

</beans>

dbinfo.properties:

#mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=

#hibernate
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.useUnicode=true
hibernate.characterEncoding=utf-8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring整合Hibernate是一种常见的Java开发组合,通过将SpringHibernate框架结合起来,可以实现更加灵活、高效的应用程序开发。下面是一个简单的Spring整合Hibernate的示例。 首先,我们需要创建一个Spring的配置文件applicationContext.xml,配置Hibernate的会话工厂、数据源以及其他相关的Bean。在该配置文件中,我们可以指定数据源、事务管理器,并定义Hibernate的会话工厂,以及设置SessionFactory所需要的Hibernate属性。 接下来,我们需要创建一个Hibernate的配置文件hibernate.cfg.xml,用于设置数据库连接、持久化实体类的映射关系等。在该配置文件中,我们可以指定数据库连接的URL、用户名和密码,还可以定义实体类与数据库表之间的映射关系。 然后,我们需要创建实体类,这些实体类将与数据库表对应。我们需要使用注解或XML来映射实体类与数据库表之间的字段关系。 接下来,在DAO层中定义接口和实现类。接口用于声明数据库操作的方法,而实现类则负责具体的数据库操作,包括增删改查等。在实现类中,我们可以使用Hibernate的API和查询语言来访问数据库,实现对数据库的操作。 最后,在Service层中定义业务逻辑的方法。Service层负责处理业务逻辑,并调用DAO层的方法访问数据库。在Service层中,我们可以通过@Transactional注解来定义事务的边界,保证数据库操作的一致性和完整性。 通过以上步骤,我们就完成了Spring整合Hibernate的基本配置和代码编写。在运行项目时,Spring会自动加载配置文件并创建相关的对象,同时会自动管理事务和会话等。 通过Spring整合Hibernate,我们可以充分发挥SpringHibernate各自的优势,实现数据库访问的灵活性、可扩展性和高性能。它们共同为Java开发提供了一个强大的框架,使得开发者能够更加便捷地开发出功能完善、高效稳定的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

FF小迷糊吖~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值