基于注解的SpringMVC整合JPA
转载位置:http://www.blogjava.net/sxyx2008/archive/2010/11/02/336768.html
实体类
Department
package com.sj.bean; import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table; @Entity
@Table(name="department",catalog="sj")
public class Department { private int id;
private String name;
private Set<Employee> sets;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy="department",cascade=CascadeType.ALL)
public Set<Employee> getSets() {
return sets;
}
public void setSets(Set<Employee> sets) {
this.sets = sets;
} }
Employee
package com.sj.bean; import java.io.Serializable; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table; @SuppressWarnings("serial")
@Entity
@Table(name="employee",catalog="sj")
public class Employee implements Serializable{ private int id;
private String name;
private Department department;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="deptid")
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
} }
BaseDAO
package com.sj.dao; import java.util.List; public interface BaseDAO<T> { List<T> listAll();
Object findById(Class<T> c,int id);
boolean save(Object object);
boolean update(Object object);
boolean delete(Object object); }
BaseDAOImpl
package com.sj.dao; import java.util.List; import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query; import org.springframework.stereotype.Component; @Component("baseDAO")
public class BaseDAOImpl<T> implements BaseDAO<T> { @PersistenceContext(unitName="sjPU")
private EntityManager entityManager; public boolean delete(Object object) {
try {
entityManager.remove(object);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} public Object findById(Class<T> c,int id) {
try {
return entityManager.find(c, id);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public boolean save(Object object) {
try {
entityManager.persist(object);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} public boolean update(Object object) {
try {
entityManager.merge(object);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} @SuppressWarnings("unchecked")
public List<T> listAll() {
try {
Query query=entityManager.createQuery(" from Employee ");
return query.getResultList();
} catch (Exception e) {
e.printStackTrace();
}
return null;
} }
BaseService
package com.sj.service; import java.util.List; public interface BaseService<T> { List<T> listAll();
Object findById(Class<T> c,int id);
boolean save(Object object);
boolean update(Object object);
boolean delete(Object object);
}
BaseServiceImpl
package com.sj.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import com.sj.dao.BaseDAO; @Component("baseServiceImpl")
public class BaseServiceImpl<T> implements BaseService<T>{ @Resource(name="baseDAO")
private BaseDAO<T> baseDAO; public BaseDAO<T> getBaseDAO() {
return baseDAO;
} public void setBaseDAO(BaseDAO<T> baseDAO) {
this.baseDAO = baseDAO;
} @Transactional(propagation=Propagation.REQUIRED)
public boolean delete(Object object) {
return baseDAO.delete(object);
} @Transactional(propagation=Propagation.REQUIRED)
public Object findById(Class<T> c, int id) {
return baseDAO.findById(c, id);
} @Transactional(propagation=Propagation.REQUIRED)
public List<T> listAll() {
return baseDAO.listAll();
} @Transactional(propagation=Propagation.REQUIRED)
public boolean save(Object object) {
return baseDAO.save(object);
} @Transactional(propagation=Propagation.REQUIRED)
public boolean update(Object object) {
return baseDAO.update(object);
} }
EmployeeAction
package com.sj.action; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import com.sj.bean.Employee;
import com.sj.service.BaseService; @Controller
@RequestMapping("/employee.action")
public class EmployeeAction { @SuppressWarnings("unchecked")
@Resource(name="baseServiceImpl")
private BaseService service; @SuppressWarnings("unchecked")
@RequestMapping(method=RequestMethod.GET,params="method=listAll")
public ModelAndView listAll(){
List<Employee> list=service.listAll();
return new ModelAndView("list").addObject("list", list);
} @ResponseBody
@RequestMapping(params="method=listOther")
public String listOther(){
String str="<font color='red'>HelloWorld</font>";
return str;
}
}
TestApp
package com.sj.test; import javax.annotation.Resource; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.sj.bean.Department;
import com.sj.bean.Employee;
import com.sj.service.BaseService; @ContextConfiguration(locations="file:D:\\Program Files\\MyEclipse 8.5-workspace\\sj\\WebRoot\\WEB-INF\\applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class TestApp { @SuppressWarnings("unchecked")
@Resource(name="baseServiceImpl")
BaseService baseService; @Test
public void save(){
Employee employee=new Employee();
employee.setName("张三");
Department department=new Department();
department.setName("软件测试组");
employee.setDepartment(department);
baseService.save(employee);
} @SuppressWarnings("unchecked")
@Test
public void query(){
Employee employee=(Employee) baseService.findById(Employee.class, 2);
System.out.println(employee.getId()+"\t"+employee.getName()+"\t"+employee.getDepartment().getName());
} }
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/>
<context:component-scan base-package="com.sj.*"/>
<aop:aspectj-autoproxy/> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="sjPU" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
dispatcherServlet-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.sj.action"/>
<bean id="defaultAnnotationHandlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
<value>text/xml</value>
<value>text/plain</value>
</list>
</property>
</bean>
</list>
</property>
</bean> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"></property>
<property name="prefix" value="/"></property>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
</bean> </beans>
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping> </web-app>
src/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0"> <persistence-unit name="sjPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sj" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit> </persistence>
list.jsp
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>雇员信息列表</title>
</head>
<body>
<c:if test="${empty requestScope.list}">
对不起,没有要显示的记录!!!!
</c:if>
<c:if test="${!empty requestScope.list}">
<c:forEach items="${requestScope.list}" var="s">
<c:out value="${s.id}"/>
<c:out value="${s.name}"/>
<c:out value="${s.department.name}"/>
<br/>
</c:forEach>
</c:if>
</body>
</html>
这里重点关注applicationContext.xml、dispatcherServlet-servlet.xml、EmployeeAction。其中dispatcherServlet-servlet.xml文件的命名规则遵循web.xml中配置的dispatcherServlet servlet的servlet-name属性的值。dispatcherServlet-servlet.xml里面配置了开启SpringMVC的注解解析器以及视图渲染器,和处理response时返回给浏览器的头信息.
基于注解的SpringMVC整合JPA的更多相关文章
- SpringMVC札集(03)——基于注解的SpringMVC入门完整详细示例
自定义View系列教程00–推翻自己和过往,重学自定义View 自定义View系列教程01–常用工具介绍 自定义View系列教程02–onMeasure源码详尽分析 自定义View系列教程03–onL ...
- 基于注解的springmvc开发
原理简析 1. 背景知识:org.springframework.web.ServletContainerInitializer接口 在基于注解的servlet开发中,ServletContainer ...
- 基于注解的SpringMVC简单介绍
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request请 ...
- SpringMVC学习总结(四)——基于注解的SpringMVC简单介绍
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是 DispatcherServlet,DispatcherServlet负责转发每一个Request ...
- 【转载】基于注解的SpringMVC简单介绍
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request请 ...
- Spring基于注解及SpringMVC
1.使用注解 (1)组件扫描 指定一个包路径,Spring会自动扫描该包 及其子包所有组件类,当发现组件类定义前有 特定的注解标记时,就将该组件纳入到Spring 容器.等价于原有XML配置中的< ...
- 基于注解的SpringMVC
相比传统的继承Controller体系中某些类的方式,SpringMVC的注解具有以下优点: 1.Controller不再需要继承某个特定类,只是简单的POJO. 2.请求映射的配置非常方便灵活. 3 ...
- Spring基于注解ehCache缓存整合
注解的使用参照:http://blog.csdn.net/wjacketcn/article/details/50945887 (侵删) ehCache是纯java实现的缓存组件,spring从3.1 ...
- spring in action 第五章基于注解搭建SpringMvc环境
request的生命历程
随机推荐
- app配置智能硬件的解决方案
随着越来越多的智能硬件产品上市,越来越多的硬件都戴上了智能的帽子,什么智能插座,智能音箱,智能称等等.凡是所谓的智能,都是通过wifi或者蓝牙来连接互联网,其中蓝牙也只能算是手机的附属品吧.主要还是硬 ...
- 伪元素content的应用
日常开发中,我们常用:before,:after来实现一些效果,比如 – 边框 – 图标 此时的content中只是为了伪元素能渲染出来而声明 1 2 3 div:before{ content: & ...
- PHP定时执行任务/Cron Job
对于PHP本身并没有一套解决方案来执行定时任务,不过是借助sleep函数完成的.这种方就是要提前做一些配置,如实现过程: ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执 ...
- DICOM开源库
转载于 http://blog.csdn.net/jackmacro/article/details/5850142 Developers used to search for libraries , ...
- 【信息学奥赛一本通】第三部分_队列 ex2_3produce 产生数
给出一个整数n(n<=2000)(代码可适用n<=10^31)和k个变换规则(k<=15). 规则:1.1个数字可以变换成另1个数字: 2.规则中右边的数字不能为零. BFS #in ...
- Kinetic使用注意点--collection
new Collection() 扩展了数组,主要用于配合new Container().get()使用 方法: each(func):遍历数组,执行回调函数.回调函数接收两个值,节点和索引. toA ...
- go语言实现的目录共享程序
其实程序很小,只不过是想写点东西了.后天晚上要回学校考试了,转眼已经出来了69天了,2个月多一点.工资加上老妈赞助的钱,不知道能不能买台电脑,作为程序员一直用着i3-3217u实在难受.回去找同学拷点 ...
- nginx+php-fpm 502 bad gateway
输出日志配置: http://blog.csdn.net/wzy_1988/article/details/8486888 解决方案: http://www.cnblogs.com/jackluo/p ...
- C# 读XML文件
/// <summary> /// xml文件路径+名称 /// </summary> public void ReadXml(string xmlname) { try { ...
- bnuoj 20832 Calculating Yuan Fen(暴力模拟)
http://www.bnuoj.com/bnuoj/problem_show.php?pid=20832 [题意]: 给你一串字符串,求一个ST(0<ST<=10000),对字符串中字符 ...