Spring4+SpringMVC4+hibernate4整合

6 篇文章 0 订阅
4 篇文章 0 订阅

源码下载:https://github.com/rj2017211811/springmvc-hibernate
1.项目的目录和jar包
在这里插入图片描述

在这里插入图片描述
2.web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:beans.xml</param-value>
	
</context-param>
<listener>

	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
	<servlet-name>action</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	
	<init-param>
		<!-- 把springmvc的配置文件放在类路径下,配置文件默认是放在/WEB-INF/下的 -->
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mvc.xml</param-value>
		
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet> 

<servlet-mapping>
	<servlet-name>action</servlet-name>
	<url-pattern>/</url-pattern>

</servlet-mapping>

  <display-name>springmvcdb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.spring-mvc.xml文件:配置spring-mvc

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

	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
				
				http://www.springframework.org/schema/mvc
				http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<!-- 自动扫描 -->
	<context:component-scan
		base-package="per.czt.springmvc.web.controller,test" />


	<!-- 注解驱动 -->


	<mvc:annotation-driven />

	<!-- 资源管理 -->
	<mvc:resources location="/resources/"
		mapping="/resources/**"></mvc:resources>
	<mvc:resources location="/upload/" mapping="/upload/**"></mvc:resources>
	<!-- 上传文件解析器 -->
	<!-- 设置上传文件最大值 1M=1*1024*1024(B)=1048576 bytes -->
	 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>


	<!-- 内部资源视图解析器 prefix+logicName+suffix /WEB-INF/jsps+index+.jsp -->
	<bean id="internalResourceViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="/WEB-INF/jsps/" />
		<!-- 后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

4.beans.xml文件:配置hibernate

<?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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jaxws="http://cxf.apache.org/jaxws"
	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-4.0.xsd
		http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.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="per.czt.springmvc.dao,per.czt.springmvc.service" />
		<!-- 开启注释处理器 -->
		<context:annotation-config />
		<!-- 配置数据源 -->
		
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springmvcdb?useSSL=false&amp;serverTimezone=UTC&amp;characterEncoding=utf-8"></property>
		<property name="username" value="root"></property>
	 <property name="password" value="123456"></property> 
 </bean>

	<!-- 开启文件上  -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource"><ref bean="dataSource" /></property>
		<!-- 扫描实体(pojo) -->
		<property name="namingStrategy">
		<bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>
		</property>
		<property name="hibernateProperties">
			
			<props>
			<!-- <prop key="hibernate.show_sql">org.hibernate.dialect.MySQLInnoDBDialect</prop> -->
	        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
			<prop key="hibernate.show_sql">true</prop>
			<!--  <prop key="hibernate.format_sql">true</prop>-->
			<!--  <prop key="hibernate.hbm2ddl.auto">update</prop>-->
			
			</props>
		</property>
		<!-- 自动扫描实体包 -->
		
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:per/czt/springmvc/domain</value>
			</list>
		</property>
	</bean>
	<bean id="personDao" class="per.czt.springmvc.dao.PersonDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<!-- spring事物管理 -->
		<tx:attributes>
		
			<tx:method name="add*" />
			<tx:method name="save*" />
			<tx:method name="Save*" />
			<tx:method name="update*" />
			<tx:method name="modify*" />
			<tx:method name="edit*" />
			<tx:method name="delete*" />
			<tx:method name="remove*" />
			<tx:method name="change*" />
			<tx:method name="repair" />
			<tx:method name="deleteAndRepair" />
			<tx:method name="login*" />
			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
			<tx:method name="datagrid*" propagation="SUPPORTS" />
			<tx:method name="*" propagation="SUPPORTS" />
			<!-- 为hibernate添加事物管理 -->
			<tx:method name="get*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="up*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="count*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	<!-- 切入点 -->
	<aop:config proxy-target-class="true">
		<aop:pointcut id="transactionPointcut" expression="execution(* per.czt.springmvc.service.*.*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut"
			advice-ref="transactionAdvice" />
	</aop:config>

	<!-- 注解方式配置事物 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<!-- <tx:annotation-driven transaction-manager="transactionManager1"/> -->
</beans>

5.person对象和Person.hbm.xml文件(pojo对象与数据库中的表一一对应)
Person.class

package per.czt.springmvc.domain;

public class Person {
	private Integer id;
	private String name;
	private Integer age;

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	
}

Person.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 映射文件需要dtd指定格式 -->
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="per.czt.springmvc.domain">
	<class name="Person" lazy="true" table="person">
		<id name="id" column="id" type="java.lang.Integer">
			<generator class="identity"></generator>
		</id>
		<property name="name" type="java.lang.String">
			<column name="name" />
		</property>
		<property name="age" type="java.lang.Integer">
			<column name="age" />
		</property>
		
	</class>

</hibernate-mapping>

6.dao层:定义一个接口,然后实现接口,获取sessionFactory(在bean.xml配置bean)实现对数据库的操作
PersonDao

package per.czt.springmvc.dao;

import java.util.List;

import per.czt.springmvc.domain.Person;

public interface PersonDao {
	public List<Person> listAll(String hql);
	public Person getById(Integer id);
	public void saveOrUpdate(Person p);
	public void deleteById(Integer id);
	
}

PersonDaoImpl

package per.czt.springmvc.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import per.czt.springmvc.domain.Person;

@Repository("personDao")

public class PersonDaoImpl  implements PersonDao {
	
	
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<Person> listAll(String hql) {
		System.out.println("sessionFactory:"+sessionFactory);
		System.out.println("hql:"+hql);
		System.out.println(" sessionFactory.getCurrentSession():"+ sessionFactory.getCurrentSession());
		List<Person> personList=(List<Person>) sessionFactory.getCurrentSession().createQuery(hql).list();
		System.out.println("personList:"+personList.size());
		return personList;
	}

	@Override
	public Person getById(Integer id) {
		
		return (Person)sessionFactory.getCurrentSession().get(Person.class, id);
	}

	@Override
	public void saveOrUpdate(Person p) {
		sessionFactory.getCurrentSession().saveOrUpdate(p);
		
	}

	@Override
	public void deleteById(Integer id) {
		sessionFactory.getCurrentSession().delete(this.getById(id));
		
	}

}

7.servic层:对dao层的结果处理,这里也是接口调用
PersonService

package per.czt.springmvc.service;

import java.util.List;

import per.czt.springmvc.domain.Person;

public interface PersonService {
	public List<Person> listAll(String hql);
	public Person getById(Integer id);
	public void saveOrUpdate(Person p);
	public void deleteById(Integer id);
}

PersonServiceImpl

package per.czt.springmvc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import per.czt.springmvc.dao.PersonDao;
import per.czt.springmvc.dao.PersonDaoImpl;
import per.czt.springmvc.domain.Person;

@Service("personService")
public class PersonServiceImpl implements PersonService {
	
	@Resource(name="personDao")
	private PersonDao personDao;
	
	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	@Override
	public List<Person> listAll(String hql) {
		
		System.out.println("personDao:"+personDao);
		return personDao.listAll(hql);
	}

	@Override
	public Person getById(Integer id) {
		// TODO Auto-generated method stub
		return personDao.getById(id);
	}

	@Override
	public void saveOrUpdate(Person p) {
		personDao.saveOrUpdate(p);

	}

	@Override
	public void deleteById(Integer id) {
		personDao.deleteById(id);

	}

}

8.controller层:调用service,并且将结果显示到view层,即jsp页面
PersonController

package per.czt.springmvc.web.controller;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import per.czt.springmvc.domain.Person;
import per.czt.springmvc.service.PersonService;


@Controller
@RequestMapping("/person")
public class PersonController {
	
	private PersonService personService;
	
	
     
	@RequestMapping("/listAll")
	public String listAll(Model model)
	{
		ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
		personService=(PersonService) ac.getBean("personService");
		System.out.println("personService1:"+personService);
		System.out.println("personService:"+personService);
		List<Person> personList=personService.listAll("from Person");
		System.out.println("personList.size()"+personList);
		model.addAttribute(personList);
		return "person/personList";
		
	}

}

9.view层:显示controller层返回的结果
person.jsp(在WEB-INF/person下)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<tbody>

			<tr>
				<th>id</th>
				<th>name</th>
				<th>age</th>
			
			</tr>
			<c:forEach items="${personList }" var="person">
				<tr>
					<td>${person.id }</td>
					<td>${person.name }</td>
					<td>${person.age }</td>
				
				</tr>

			</c:forEach>

		</tbody>
	</table>
</body>
</html>

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>
	
	<a href="${pageContext.request.contextPath }/person/listAll.action">显示列表</a>
</body>
</html>

10.在index.jsp点击显示列表,即可显示所有person了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值