springmvc + spring + hibernate 实现简单的增删改查和分页

最近在学习springmvc,spring,hibernate这几个框架,参考了网上很多资料,最终做出来了一个算是可以用的玩意。想把这个过程记录下来,顺便理顺下自己做出这个玩意的过程。


这是整个项目的结构

springmvc + spring + hibernate 实现简单的增删改查和分页_第1张图片

pom.xml


  4.0.0
  com.wzq.hello
  ssh
  war
  0.0.1-SNAPSHOT
  ssh Maven Webapp
  http://maven.apache.org
	
		
			junit
			junit
			3.8.1
			test
		
		
			org.springframework
			spring-context
			${spring.version}
		
		
			org.springframework
			spring-core
			${spring.version}
		
		
			org.springframework
			spring-beans
			${spring.version}
		
		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-webmvc
			${spring.version}
		

		
			javax.servlet
			jstl
			1.2
		

		
		
			c3p0
			c3p0
			0.9.1.2
		


		
			org.springframework
			spring-orm
			${spring.version}
		

		
		
			org.hibernate
			hibernate-core
			5.2.12.Final
		

		
		
			javax.annotation
			javax.annotation-api
			1.2
		

		
		
			javax.servlet
			servlet-api
			2.5
			provided
		
		
		
			mysql
			mysql-connector-java
			5.1.45
		

	
	
		springmvc
	
	
		5.0.4.RELEASE
	



web.xml



	Archetype Created Web Application

	
	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		true
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	
	
		encodingFilter
		/*
	
	

	
	
		contextConfigLocation
		classpath:beans.xml
	
	
	
	
	
		openSession
		org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
	
	
		openSession
		/*
	
	
	
	
	
		org.springframework.web.context.ContextLoaderListener
	
	

	
	
		default
		*.css
	
	
		default
		*.js
	
	
		default
		*.img
	
	
	
	
	
		spring
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:spring-mvc.xml
		
	
	
		spring
		/
	
	




springmvc.xml




	
		
		
	


	
		
		
		
		
	
	
	



datasource.xml





	
		
		
		
		
		
		
		
		
	
	
		
		
		
			
				${hibernate.hbm2ddl.auto}
				${hibernate.dialect}
				${hibernate.show_sql}
				${hibernate.format_sql}
				false
			
		
	
	
		
	
	



datasource.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test
user=root
password=1011012379
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true

beans.xml



	
		
	

	
	
		
			
				classpath:datasource.properties
			
		
	
	

实体类

package com.wzq16.hello.model;

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


@Entity
@Table(name="consumer")
public class Consumer {
	@Id
	@Column(name="id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;
	
	@Column(unique=true)
	private String consumerId;
	
	@Column
	private String consumerName;
	
	@Column(nullable = true)
	private int consumerAge;
	
	@Column(nullable = true)
	private String consumerGender; 
	

	public Integer getId() {
		return id;
	}

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

	public String getConsumerId() {
		return consumerId;
	}

	public void setConsumerId(String consumerId) {
		this.consumerId = consumerId;
	}

	public String getConsumerName() {
		return consumerName;
	}

	public void setConsumerName(String consumerName) {
		this.consumerName = consumerName;
	}

	public int getConsumerAge() {
		return consumerAge;
	}

	public void setConsumerAge(int consumerAge) {
		this.consumerAge = consumerAge;
	}

	public String getConsumerGender() {
		return consumerGender;
	}

	public void setConsumerGender(String consumerGender) {
		this.consumerGender = consumerGender;
	}

}
package com.wzq16.hello.model;

import java.util.List;

public class PageBean {

	private Integer currentPage;
	private Integer totalPages;
	private Integer allRowsCounts;
	private Integer pageSize = 5;
	private List list;

	public static int currentPage(int page) {
		return page == 0 ? 1 : page;
	}

	public static int curOffset(int pageSize, int currentPage) {
		return pageSize * (currentPage - 1);
	}

	public static int getTotalPages(int allRowsCounts, int pageSize) {
		return allRowsCounts % pageSize == 0 ? allRowsCounts / pageSize : allRowsCounts / pageSize + 1;
	}

	public Integer getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(Integer currentPage) {
		this.currentPage = currentPage;
	}

	public Integer getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(Integer totalPages) {
		this.totalPages = totalPages;
	}

	public Integer getAllRowsCounts() {
		return allRowsCounts;
	}

	public void setAllRowsCounts(Integer allRowsCounts) {
		this.allRowsCounts = allRowsCounts;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}
}


Dao层

package com.wzq16.hello.dao;

import java.util.List;

import com.wzq16.hello.model.Consumer;

public interface ConsumerDao {

	public void addConsumer(Consumer consumer);

	public void removeConsumer(Consumer consumer);

	public void updateConsumer(Consumer consumer);

	public List getAllConsumers();

	public void removeConsumerById(String consumerId);

	public Consumer getConsumer(String consumerId);

	public List findForPage(String hql, int offset, int length);

	public int findAllRowsCount(String hql);
}
package com.wzq16.hello.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.wzq16.hello.model.Consumer;

@Repository("consumerDao")
public class ConsumerDaoImpl implements ConsumerDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void addConsumer(Consumer consumer) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().save(consumer);
	}

	@Override
	public void removeConsumer(Consumer consumer) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().remove(consumer);
	}

	@Override
	public void removeConsumerById(String consumerId) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().createQuery("delete Consumer where consumerId = ?").setParameter(0, consumerId)
				.executeUpdate();
	}

	@Override
	public void updateConsumer(Consumer consumer) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().merge(consumer);
	}

	@Override
	public List getAllConsumers() {
		// TODO Auto-generated method stub

		return sessionFactory.getCurrentSession().createQuery("from Consumer", Consumer.class).getResultList();
	}

	@Override
	public Consumer getConsumer(String consumerId) {
		// TODO Auto-generated method stub
		return (Consumer) sessionFactory.getCurrentSession().createQuery("from Consumer where consumerId = :consumerId")
				.setParameter("consumerId", consumerId).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List findForPage(String hql, int offset, int length) {
		// TODO Auto-generated method stub
		return (List) sessionFactory.getCurrentSession().createQuery(hql).setFirstResult(offset)
				.setMaxResults(length).list();
	}

	@Override
	public int findAllRowsCount(String hql) {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession().createQuery(hql).list().size();
	}

}


service层

package com.wzq16.hello.service;


import java.util.List;

import com.wzq16.hello.model.PageBean;
import com.wzq16.hello.model.Consumer;


public interface ConsumerService {

	public void addConsumer(Consumer consumer);
	public List getAllConsumers();
	public void removeConsumerById(String consumerId);
	public Consumer getConsumer(String consumerId);
	public void updateConsumer(Consumer consumer);
	public void removeConsumer(Consumer consumer);
	
	public PageBean queryForPage(int currentPage);
}
package com.wzq16.hello.service;

import java.util.List;

import javax.annotation.Resource;

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

import com.wzq16.hello.dao.ConsumerDao;
import com.wzq16.hello.model.PageBean;
import com.wzq16.hello.model.Consumer;

@Service("consumerService")
@Transactional
public class ConsumerServiceImpl implements ConsumerService {

	@Resource(name = "consumerDao")
	private ConsumerDao consumerDao;

	@Override

	public void addConsumer(Consumer consumer) {
		// TODO Auto-generated method stub
		consumerDao.addConsumer(consumer);
	}

	public void removeConsumer(Consumer consumer) {
		consumerDao.removeConsumer(consumer);
	}

	public void removeConsumerById(String consumerId) {
		consumerDao.removeConsumerById(consumerId);
	}

	public void updateConsumer(Consumer consumer) {
		consumerDao.updateConsumer(consumer);
	}

	public Consumer getConsumer(String consumerId) {
		return consumerDao.getConsumer(consumerId);
	}

	@Override
	public List getAllConsumers() {
		// TODO Auto-generated method stub
		return consumerDao.getAllConsumers();
	}

	@Override
	public PageBean queryForPage(int curPage) {
		// TODO Auto-generated method stub
		final int pageSize = 5;
		String hql = "from Consumer";
		int allRowsCounts = consumerDao.findAllRowsCount(hql);
		int currentPage = PageBean.currentPage(curPage);
		int currentOffset = PageBean.curOffset(pageSize, currentPage);
		int totalPages = PageBean.getTotalPages(allRowsCounts, pageSize);
		List students = consumerDao.findForPage(hql, currentOffset, pageSize);
		PageBean pageBean = new PageBean();
		pageBean.setAllRowsCounts(allRowsCounts);
		pageBean.setCurrentPage(currentPage);
		pageBean.setTotalPages(totalPages);
		pageBean.setAllRowsCounts(allRowsCounts);
		pageBean.setList(students);
		return pageBean;
	}

}


controller

package com.wzq16.hello.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wzq16.hello.model.Consumer;
import com.wzq16.hello.service.ConsumerService;

@Controller
public class ConsumerController {

	@Autowired
	private ConsumerService consumerService;
	
	@RequestMapping("/main")
	public String main(String username, String password) {
		if(username.equals("wzq") && password.equals("1011012379")) {
			return "main";
		}
		return "error";
	}
	
	@RequestMapping("/consumerInfo")
	public String consumerInfo(@RequestParam(value="currentPage",defaultValue="1")int currentPage, Model model) {
		model.addAttribute("pageBean", consumerService.queryForPage(currentPage));
		return "consumerInfo";
	}
	
	@RequestMapping("/addConsumer")
	public String addConsumer(int currentPage,Model model) {
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("consumer", new Consumer());
		return "addConsumer";
	}
	
	@RequestMapping("/saveConsumer")
	public String saveConsumer(Consumer consumer, int currentPage, Model model) {
		consumerService.addConsumer(consumer);
		model.addAttribute("currentPage", currentPage);
		return "redirect:consumerInfo";
	}
	
	@RequestMapping("/editConsumer")
	public String editConsumer(String consumerId, int currentPage, Model model) {
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("consumer", consumerService.getConsumer(consumerId));
		return "editConsumer";
	}
	
	@RequestMapping("/updateConsumer")
	public String updateConsumer(Consumer consumer, int currentPage,Model model) {
		consumerService.updateConsumer(consumer);
		model.addAttribute("currentPage", currentPage);
		return "redirect:consumerInfo";
	}
	
	@RequestMapping("/removeConsumerById")
	public String removeConsumerById(String consumerId, int currentPage,Model model) {
		consumerService.removeConsumerById(consumerId);
		if(consumerService.queryForPage(currentPage).getList().size() == 0) {
			currentPage = currentPage - 1;
		}
		model.addAttribute("currentPage", currentPage);
		return "redirect:consumerInfo";
	}
}


JSP文件

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here







main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


用户信息


consumerInfo.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


	
用户ID 姓名 性别 年龄 编辑 删除
${consumer.consumerId } ${consumer.consumerName } ${consumer.consumerAge } ${consumer.consumerGender } 编辑 删除
没有任何用户信息
${requestScope.pageBean.currentPage }页/${requestScope.pageBean.totalPages }页   [首页]   [上一页]   [下一页]   [尾页]  


addConsumer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>






Insert title here



editConsumer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>







Insert title here



error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


未知用户

当然这个玩意还有很多不足,以后再慢慢完善吧

你可能感兴趣的:(javaee)