`

springmvc和hibernate的整合(annotation)

 
阅读更多

采用sprng MVC开发项目时,通常都会采用注解的方式,这样可以大大提高开发效率,实现零配置。下面从零开始重新做一个spring MVC的配置。这个项目完全采用注解的方式开发。

第一步,导入springhibernatejar(spring.jar, spring-webmvc.jar, commons-logging-1.0.4.jar。其他jar包为hibernate相关jar)

 

第二步,项目配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name>springmvc_004_hibernate_annotation</display-name>
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

第三步,springMVC配置文件spring-mvc.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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
	<!-- 对com.test包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="com.test" />
	
	<!-- 数据源 -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations" value="classpath:jdbc.properties"></property>
	</bean>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<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.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- key的名字前面都要加hibernate. -->
<!-- 				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</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="packagesToScan">
			<value>com.test.model</value>
		</property>
	</bean>

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 配置事务边界 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<tx:annotation-driven transaction-manager="txManager" />

	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
			<!-- get开头的方法不需要在事务中运行,有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的 -->
			<tx:method name="*" /><!-- 其他方法在事务中运行 -->
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:pointcut id="businessService" expression="execution(public * com.test.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
	</aop:config>
	
	<!-- 页面View层基本信息设定 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

 

第四步,实体类Employee.java

package com.test.model;

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

@Entity
public class Employee {
	@Id
	@GeneratedValue
	private int id;
	private String name;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

第五步,DAOEmployeeDao.java

package com.test.dao;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.test.model.Employee;

@Component("employeeDao")
public class EmployeeDao {
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource(name = "hibernateTemplate")
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void add(Employee employee) {
		hibernateTemplate.save(employee);
	}

}

 

第六步,serviceEmployeeService.java

package com.test.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.test.dao.EmployeeDao;
import com.test.model.Employee;

@Component("employeeService")
public class EmployeeService {
	private EmployeeDao employeeDao;

	public EmployeeDao getEmployeeDao() {
		return employeeDao;
	}

	@Resource(name = "employeeDao")
	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

	public void add(String name) {
		Employee employee = new Employee();
		employee.setName(name);
		employeeDao.add(employee);
	}
}

 

第七步,控制器HelloController.java

package com.test.controller;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.service.EmployeeService;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

	private EmployeeService employeeService;

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	@Resource(name = "employeeService")
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	@RequestMapping(params = "method=request")
	public String request(String name) {
		try {
			employeeService.add(new String(name.getBytes("iso8859-1"), "GBK"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "result";
	}

}

第八步,jsp目录下创建result.jsp文件

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>结果</title>
</head>
<body>
	<h1>success</h1>
</body>
</html>

 

第九步,首页index.jsp文件

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>首页</title>
</head>
<body>
	<form action="employee" method="get">
		<input type="text" name="name">
		<input type="hidden" name="method" value="request">
		<input type="submit" value="提交">
	</form>
</body>
</html>

在浏览器中输入:

http://127.0.0.1:9900/springmvc_004_hibernate_annotation/index.jsp进行测试

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics