`
yaerfeng1989
  • 浏览: 230922 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

通过SpringMVC整合基于注解的JPA的实例教程代码下载

阅读更多

实体类
原创整理不易,转载请注明出处:通过SpringMVC整合基于注解的JPA的实例教程代码下载

代码下载地址:http://www.zuidaima.com/share/1751862510177280.htm

Department

package com.zuidaima.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.zuidaima.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.zuidaima.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.zuidaima.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.zuidaima.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.zuidaima.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 , );
 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 - </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> </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时返回给浏览器的头信息.
点我下载工程代码

1
3
分享到:
评论

相关推荐

    【孔浩老师】SpringMVC整合Hibernate(全注解)实现用户管理管理

    本教程由孔浩老师指导,通过全注解的方式整合这两个框架,实现了一个简单的用户管理系统,并引入了分页功能和日志处理。\n\n一、SpringMVC与Hibernate整合\n\n1. **配置SpringMVC**:首先,我们需要在SpringMVC的...

    spring3.0 mvc中文实例教程

    4. **注解驱动的数据格式化**:通过注解如`@DateTimeFormat`和`@NumberFormat`,可以方便地进行日期和货币格式转换。 5. **JPA 2.0支持**:集成对Java Persistence API 2.0的支持,优化了数据库操作。 【配置Spring...

    将_Shiro_作为应用的权限基础_五:SpringMVC+Apache_Shiro+JPA(hibernate)整合配置

    本文旨在详细介绍如何将Apache Shiro整合到基于SpringMVC和JPA(hibernate)的应用程序中,为系统提供安全控制机制。通过本教程,您将了解关键配置文件的作用及其配置细节,包括`web.xml`、`applicationContext.xml`...

    springMVC实例项目

    **SpringMVC 实例项目详解** SpringMVC是Spring框架的一部分,它是一个基于模型-视图-控制器(MVC)架构的Web应用开发框架。在本实例项目中,你将深入学习SpringMVC的实现原理及其核心功能,涵盖从基础到进阶的各个...

    金典springMVC+Hibernate框架实例

    【金典springMVC+Hibernate框架实例】是一个深入讲解企业级应用开发的教程,它结合了Spring MVC和Hibernate两大主流框架,旨在帮助开发者构建高效、稳定且易于维护的Java Web应用。Spring MVC作为Spring框架的一部分...

    spring_springMVC_hibernate

    JPA允许你通过注解在实体类上定义数据表的映射,简化了数据库交互。 总的来说,这个压缩包可能是为了帮助开发者理解如何将Spring、Spring MVC和Hibernate进行整合,从而构建一个完整的Java Web应用程序。通过学习和...

    SpringMVC+Hibernate+Spring+maven框架搭建

    在IT行业中,构建高效、可维护的Web应用是至关重要的,而Spring MVC、Hibernate和Spring框架的整合使用正是实现这一目标的有效方式。本教程将详细阐述如何利用这些技术栈搭建一个完整的开发环境,并提供日后参考。 ...

    SpringBoot+SSM三个框架实例

    总之,"SpringBoot+SSM三个框架实例"是一个实用的教程,它展示了如何在SpringBoot环境中有效地整合传统的SpringMVC和Mybatis,帮助开发者掌握现代Java Web开发的最佳实践。通过实际操作,你可以更好地理解这些框架的...

    springmvc_web_ibatis

    标题 "springmvc_web_ibatis" 暗示了我们即将探讨的是一个关于Spring MVC、Web开发以及MyBatis集成的项目或教程。这个项目可能是为了展示如何在Java Web应用程序中有效地利用这三个技术来构建数据驱动的Web应用。...

    基于SSM+VUE的社区互助系统源码.zip

    这是一个基于SSM(Spring、SpringMVC、MyBatis)和Vue.js开发的社区互助系统的源码项目。SSM框架是Java后端开发中的经典组合,Spring提供了依赖注入和事务管理,SpringMVC处理HTTP请求和响应,MyBatis则作为持久层...

    spring3.0MVC中文教程.doc

    Spring3.0 MVC教程通常分为多个部分,包括对框架基础的介绍、创建基本的"Hello World"应用、表单处理、Tiles支持、国际化和本地化、主题设置,以及整合Hibernate进行数据库操作等。这些教程旨在帮助开发者逐步掌握...

    sspringmvcH

    1. **依赖注入(Dependency Injection, DI)**:允许开发者通过配置文件或注解来声明组件之间的依赖关系,解耦了代码,提高了可测试性。 2. **面向切面编程(Aspect-Oriented Programming, AOP)**:提供了一个平台...

Global site tag (gtag.js) - Google Analytics