`
孟雪雪
  • 浏览: 53009 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

基于注解的SpringMVC整合JPA

阅读更多
实体类
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时返回给浏览器的头信息.
点我下载工程代码
  • sj.zip (27.4 KB)
  • 下载次数: 39
分享到:
评论
1 楼 xy_arrow 2012-08-22  
能把包 也发下吗 ? 744743291@qq.com  

相关推荐

    spring+springMVC+jpa+hibernate框架整合

    在IT领域,构建高效、可扩展的Web应用是至关重要的,而"spring+springMVC+jpa+hibernate框架整合"就是一个常见的解决方案。这个整合涉及到四个关键的技术栈:Spring框架、SpringMVC、JPA(Java Persistence API)...

    Spring SpringMVC Jpa整合Demo

    在JavaEE开发中,Spring、SpringMVC和JPA是三个非常重要的框架,它们的整合应用可以极大地提高开发效率和代码质量。这个"Spring SpringMVC Jpa整合Demo"就是一个典型的例子,它展示了如何将这三个框架协同工作,构建...

    springmvc整合jpa

    **SpringMVC与JPA整合详解** 在Java Web开发中,SpringMVC作为一款强大的Model-View-Controller框架,常用于构建高效的后端系统。而Java Persistence API (JPA) 则是Java官方推荐的ORM(对象关系映射)解决方案,它...

    springmvc+jpa 例子

    在Spring MVC应用中整合JPA,可以实现高效的数据库操作。以下是一些关键步骤: 1. **配置JPA**:在Spring配置文件中,添加JPA的供应商(如Hibernate),设置数据源、实体扫描路径等。 2. **配置DataSource**:定义...

    springMvc data jpa example

    在 "springMvc data jpa example" 中,我们将探讨如何将这两者结合使用,创建一个基于 Spring 3.1.2 和 Spring Data JPA 1.3.1 的示例应用。 首先,让我们深入了解 Spring MVC。Spring MVC 提供了一个模型-视图-...

    maven构建项目,整合springmvc jpa

    通过以上步骤,我们可以构建出一个基于Maven、SpringMVC和JPA的项目,这个项目具备了良好的模块化和解耦特性,便于团队协作和后期维护。同时,由于Maven的强大依赖管理和SpringMVC的灵活性,我们可以快速地集成其他...

    spring+springMVC+maven+jpa框架搭建

    在IT行业中,构建高效、可维护的Web应用是至关重要的,而使用Spring、SpringMVC、Maven和JPA这四个关键组件可以帮助我们实现这一目标。让我们深入探讨这些框架和工具,以及如何将它们整合在一起搭建一个完整的开发...

    spring+springmvc+jpa(hibernate)框架整合

    在Spring中整合JPA或Hibernate,可以实现对数据库的便捷操作,无需编写大量的SQL代码。 整合Spring、SpringMVC和Hibernate,首先需要在项目中引入相关依赖,通常通过Maven或Gradle来管理。在pom.xml或build.gradle...

    SpringMVC4+JPA Demo

    本Demo将详细介绍如何在SpringMVC 4项目中整合JPA,实现高效的数据操作。 首先,让我们理解这两个核心概念: 1. **SpringMVC 4**:SpringMVC是Spring框架的一部分,提供了一个用于构建Web应用程序的模型-视图-控制...

    SpringMVC+JPA+Freeemarker 纯javaConfig,无xml配置

    在本项目"SpringMVC+JPA+Freeemarker 纯javaConfig,无xml配置"中,开发者采取了一种现代化的方法,完全摒弃了XML配置,转而使用Java Config方式进行配置。这一转变使得代码更加简洁、易于理解和维护。以下将详细...

    spring3+springmvc+jpa+hibernate

    3. 实体类(Entities):这些是与数据库表映射的Java类,使用JPA注解进行配置。 4. Repository接口:基于JPA的接口,定义了对数据库的操作,例如CRUD(创建、读取、更新、删除)操作。 5. 控制器(Controllers):...

    用maven构建SpringMVC+JPA+Hibernate+Hsql+jetty的web项目

    【标题】"用maven构建SpringMVC+JPA+Hibernate+Hsql+jetty的web项目"涉及了多个核心的Java Web开发技术,这里我们将深入探讨这些技术以及如何将它们整合到一起。 1. Maven:Maven是Apache的一个开源项目,它是一个...

    非注解Springmvc+spring+hibernate 入门实例

    下面我们将深入探讨"非注解SpringMVC+Spring+Hibernate入门实例"中的关键知识点。 首先,让我们从SpringMVC开始。SpringMVC是一个Model-View-Controller架构模式的实现,用于构建Web应用程序。在非注解方式下,我们...

    spring3+springmvc+jpa2+gae

    标题 "spring3+springmvc+jpa2+gae" 指的是一个集成开发环境,它结合了Spring框架的三个核心组件以及Google App Engine (GAE)。这个项目旨在展示如何在GAE上运行一个基于Spring 3、Spring MVC和JPA 2.0的应用程序。...

    《基于注解的SpringMVC增删改DEMO源码》Maven版

    《基于注解的SpringMVC增删改DEMO源码》是针对Maven构建的Java Web项目,旨在帮助开发者理解并实践SpringMVC框架中基于注解的控制器、数据访问和事务管理等核心功能。该项目提供了完整的源代码,使得学习者能够通过...

    SpringMvc+Jpa+Hibernate+JqueryUi实战(最新代码)

    这是一个基于Java技术栈的Web应用实战项目,使用了Spring MVC、JPA、Hibernate以及Jquery UI等技术。本文将详细解析这些技术的核心概念及其在项目中的应用。 首先,Spring MVC是Spring框架的一部分,是一个用于构建...

    SpringMVC+Apache Shiro+JPA(hibernate)整合

    本文将深入探讨如何将SpringMVC、Apache Shiro以及JPA(以Hibernate为实现)进行整合,以便在实际项目中实现高效且安全的用户认证与授权功能。 首先,我们来看`SpringMVC`,它是Spring框架的一部分,专门用于处理...

    springmvc+springjpa+hibernate整合简例

    总结来说,"springmvc+springjpa+hibernate整合简例"涉及到的主要知识点包括: 1. SpringMVC的请求处理流程和配置。 2. SpringJPA的使用,包括实体和数据访问接口的定义。 3. Hibernate作为JPA提供者的配置和特性...

    shiro+springmvc整合demo

    在本示例中,"shiro+springmvc整合demo" 提供了一个基于SpringMVC和Apache Shiro的完整演示,同时结合了JPA(Java Persistence API,通过Hibernate实现)进行数据持久化。下面我们将详细探讨这些知识点。 **1. ...

    SpringMVC+Spring Data JPA+Shiro+EasyUI 简单demo

    "SpringMVC+Spring Data JPA+Shiro+EasyUI 简单demo"是一个整合了上述四个技术的Web应用示例。这个项目可能包含了以下组件: 1. **配置文件**:如`applicationContext.xml`用于配置SpringMVC和Spring Data JPA,...

Global site tag (gtag.js) - Google Analytics