栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring整合Hibernate

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 findAllCakes() {
		Query query = this.sessionFactory.getCurrentSession().createQuery("from Cake");
		List 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 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 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"%>




Insert title here


	


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"%>





Insert title here


	新 增 蛋 糕

编 号 重 量 价 格 图 片 操 作
${cake.id } ${cake.weight } ${cake.price } 修 改

删 除

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"%>




Insert title here


	
		

添加蛋糕
重 量:
价 格:
图 片:

${error }

修改蛋糕
重 量:
价 格:
图 片:

web.xml:



	
	Homework4
	
	
		index.jsp
	
	
	
		contextConfigLocation
		
            classpath*:/applicationContext.xml
        
	
	
	
		org.springframework.web.context.ContextLoaderListener
	
	
	
		springmvc
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			/WEB-INF/spring-mvc.xml
		
		1
	
	
	
		springmvc
		/
	
	
	
		CharacterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
	
	
	
		CharacterEncodingFilter
		/*
	
	
	
		openSessionInView
		org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
	
	
	
		openSessionInView
		/*
	

spring-mvc.xml:



	
	
	
	
	
	
	
	
		
	
	
	
	
		
	
	
	
	
		
		
	


applicationContext.xml:



	Spring公共配置 

	
	
	
	
		
	

	
	
	
		
		
		
		
	

	
		
		
		
		
			
				${hibernate.dialect}
				${hibernate.show_sql}
				${hibernate.format_sql}
				${hibernate.useUnicode}
				${hibernate.characterEncoding}
				thread
			
		
	
	
	
	
		
	
	


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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915408.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号