基于MAVEN的Spring整合JPA并且分页

源码地址:http://download.csdn.net/download/a295277302/9829063

1.项目结构截图



 对pom.xml文件添加jar


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sssp</groupId>
  <artifactId>sssp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sssp Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <!--配置版本号-->
  <properties>
    <mysql.version>5.1.34</mysql.version>
    <spring.version>4.3.0.RELEASE</spring.version>
    <hibernate.version>5.1.0.Final</hibernate.version>
    <querydsl.version>4.1.4</querydsl.version>
  </properties>


  <dependencies>
    <!-- Spring Framework -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
</dependency>
    
    <!-- Spring Framework end-->


    <!--alibaba start-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.19</version>
    </dependency>
    <!--alibaba end-->
<!-- c3p0  start-->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
   <groupId>com.mchange</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.5.2</version>
</dependency>
<!-- c3[0 end -->

<!-- ehcache start -->
<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache-core</artifactId>
   <version>2.6.11</version>
</dependency>
<!-- ehcache end -->

    <!--JPA start-->
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.10.4.RELEASE</version>
      </dependency>
    <!--JPA end-->


    <!--hibernate start-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-ehcache</artifactId>
   <version>${hibernate.version}</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-c3p0</artifactId>
   <version>${hibernate.version}</version>
</dependency>
    
    <!--hibernate end-->
    
    <!-- cglib start-->
    <!-- https://mvnrepository.com/artifact/cglib/cglib -->
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.6.8</version>
</dependency>
    <!-- cglib end -->
    
    <!--mysql start-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--mysql end-->
    <!--logger start-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>1.7.7</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.2</version>
    </dependency>
    <!--logger end-->
    <!--test start-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--test end-->
    <!--common start-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.3.2</version>
    </dependency>
    <!--common end-->
    <!--query dsl-->
    <dependency>
      <groupId>com.querydsl</groupId>
      <artifactId>querydsl-jpa</artifactId>
      <version>${querydsl.version}</version>
    </dependency>
    <dependency>
      <groupId>com.querydsl</groupId>
      <artifactId>querydsl-apt</artifactId>
      <version>${querydsl.version}</version>
      <scope>provided</scope>
    </dependency>
    <!--query dsl end-->
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
    
  </dependencies>


  <build>
    <finalName>testjpa</finalName>
    <plugins>
      <!--该插件可以生成querysdl需要的查询对象,执行mvn compile即可-->
      <plugin>
        <groupId>com.mysema.maven</groupId>
        <artifactId>apt-maven-plugin</artifactId>
        <version>1.1.3</version>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <configuration>
              <outputDirectory>target/generated-sources/java</outputDirectory>
              <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
            </configuration>
          </execution>
        </executions>
      </plugin>


      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>


    </plugins>
  </build>
  <repositories>
      <repository>
          <id>Sonatype</id>
          <name>Sonatype Repository</name>
          <url>http://repository.sonatype.org/content/groups/public/</url>
          <layout>default</layout>
          <releases>
              <enabled>true</enabled>
          </releases>
          <snapshots>
             <enabled>false</enabled>
          </snapshots>
     </repository>
 </repositories>
</project>


之后配置web.xml 文件


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


<!-- 配置启动 IOC 容器的 Listener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>


<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 配置字符编码过滤器 -->
<!-- 字符编码过滤器必须配置在所有过滤器的最前面! -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 配置可以把 POST 请求转为 PUT、DELETE 请求的 Filter -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 配置 OpenEntityManagerInViewFilter. 可以解决懒加载异常的问题 -->
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 配置 SpringMVC 的 DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>


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


</web-app>


添加SpringMvc配置文件

在WEB-INF下添加

springDispatcherServlet-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.htf.sssp" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>


<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>


</beans>


添加src下的资源目录下Spring Bean文件 

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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.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="com.htf.sssp">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

<!-- 配置数据源 -->
<context:property-placeholder location="classpath:db.properties"/>


<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

<!-- 配置其他属性 -->
</bean>

<!-- 配置 JPA 的 EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<property name="packagesToScan" value="com.htf.sssp"></property>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
</props>
</property>
<property name="sharedCacheMode" value="ENABLE_SELECTIVE"></property>
</bean>

<!-- 配置事务 -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>

<!-- 配置支持基于注解的事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!-- 配置 SpringData -->
<jpa:repositories base-package="com.htf.sssp"
entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>

</beans>



添加数据库连接信息  >>>>>  db.properties

jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring


添加缓存ehcache   >>>> ehcache.xml


<ehcache>


    <!-- Sets the path to the directory where cache .data files are created.


         If the path is a Java System Property it is replaced by
         its value in the running VM.


         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>




    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.


        The following attributes are required for defaultCache:


        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.


        -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />


    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts


        The following attributes are required for defaultCache:


        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.


        -->


    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.


        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />


    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->


    <!-- Place configuration for your caches following -->

</ehcache>


添加测试类  >>> SSSPTest   测试与数据库的连通情况


package com.htf.sssp.test;


import java.sql.SQLException;


import javax.sql.DataSource;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;




public class SSSPTest {

private ApplicationContext ctx = null;



{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");


}





@Test
public void testDataSource() throws SQLException {
DataSource dataSource = ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}


}


如果成功会显示:



添加实体类  >>>> Employee

package com.htf.sssp.entity;


import java.util.Date;


import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


import org.springframework.format.annotation.DateTimeFormat;


@Table(name="SSSP_EMPLOYEES")
@Entity
public class Employee {

private Integer id;
private String lastName;

private String email;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;

private Date createTime;

private Department department;


@GeneratedValue
@Id
public Integer getId() {
return id;
}


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


public String getLastName() {
return lastName;
}


public void setLastName(String lastName) {
this.lastName = lastName;
}


public String getEmail() {
return email;
}


public void setEmail(String email) {
this.email = email;
}


@Temporal(TemporalType.DATE)
public Date getBirth() {
return birth;
}


public void setBirth(Date birth) {
this.birth = birth;
}


@Temporal(TemporalType.TIMESTAMP)
public Date getCreateTime() {
return createTime;
}


public void setCreateTime(Date createTime) {
this.createTime = createTime;
}


@JoinColumn(name="DEPARTMENT_ID")
@ManyToOne(fetch=FetchType.LAZY)
public Department getDepartment() {
return department;
}


public void setDepartment(Department department) {
this.department = department;
}
}


添加实体类 >>>> Department


package com.htf.sssp.entity;


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


@Cacheable
@Table(name="SSSP_DEPARTMENTS")
@Entity
public class Department {


private Integer id;
private String departmentName;


@GeneratedValue
@Id
public Integer getId() {
return id;
}


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


public String getDepartmentName() {
return departmentName;
}


public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}


}


添加Handler >>>>> EmployeeHandler

package com.htf.sssp.haderln;


import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.htf.sssp.entity.Employee;
import com.htf.sssp.service.DepartmentService;
import com.htf.sssp.service.EmployeeService;


@Controller
public class EmployeeHandler {


@Autowired
private EmployeeService employeeService;

@Autowired
private DepartmentService departmentService;


@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){
employeeService.delete(id);
return "redirect:/emps";
}

@ModelAttribute
public void getEmployee(@RequestParam(value="id",required=false) Integer id,
Map<String, Object> map){
if(id != null){
Employee employee = employeeService.get(id);
employee.setDepartment(null);
map.put("employee", employee);
}
}

@RequestMapping(value="/emp/{id}",method=RequestMethod.PUT)
public String update(Employee employee){
employeeService.save(employee);
return "redirect:/emps";
}

@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
public String input(@PathVariable("id") Integer id, Map<String, Object> map){
Employee employee = employeeService.get(id);
map.put("employee", employee);
map.put("departments", departmentService.getAll());
return "emp/input";
}

@RequestMapping(value="/emp",method=RequestMethod.POST)
public String save(Employee employee){
employeeService.save(employee);
return "redirect:/emps";
}

@ResponseBody
@RequestMapping(value="/ajaxValidateLastName",method=RequestMethod.POST)
public String validateLastName(@RequestParam(value="lastName",required=true) String lastName){
Employee employee = employeeService.getByLastName(lastName);
if(employee == null){
return "0";
}else{
return "1";
}
}

@RequestMapping(value="/emp",method=RequestMethod.GET)
public String input(Map<String,Object> map){
map.put("departments", departmentService.getAll());
map.put("employee", new Employee());
return "emp/input";
}

@RequestMapping("/emps")
public String list(@RequestParam(value="pageNo", required=false, defaultValue="1") String pageNoStr, 
Map<String, Object> map){
int pageNo = 1;

try {
//¶Ô pageNo µÄУÑé
pageNo = Integer.parseInt(pageNoStr);
if(pageNo < 1){
pageNo = 1;
}
} catch (Exception e) {}

Page<Employee> page = employeeService.getPage(pageNo, 5);
map.put("page", page);

return "emp/list";
}

}


添加repository    >>>>>   DepartmentRepository , EmployeeRepository


package com.htf.sssp.repository;


import java.util.List;


import javax.persistence.QueryHint;


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;


import com.htf.sssp.entity.Department;


public interface DepartmentRepository extends JpaRepository<Department, Integer>{


@QueryHints({@QueryHint(name=org.hibernate.ejb.QueryHints.HINT_CACHEABLE,value="true")})
@Query("FROM Department d")
List<Department> getAll();

}


package com.htf.sssp.repository;


import org.springframework.data.jpa.repository.JpaRepository;


import com.htf.sssp.entity.Employee;


public interface EmployeeRepository extends JpaRepository<Employee, Integer> {


Employee getByLastName(String lastName);

}



添加Service >>>>   DepartmentService , EmployeeService

package com.htf.sssp.service;


import java.util.Date;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.htf.sssp.entity.Employee;
import com.htf.sssp.repository.EmployeeRepository;


@Service
public class EmployeeService {


@Autowired
private EmployeeRepository employeeRepository;

@Transactional
public void delete(Integer id){
employeeRepository.delete(id);
}

@Transactional(readOnly=true)
public Employee get(Integer id){
return employeeRepository.findOne(id);
}

@Transactional
public void save(Employee employee){
if(employee.getId() == null){
employee.setCreateTime(new Date());
}
employeeRepository.saveAndFlush(employee);
}

@Transactional(readOnly=true)
public Employee getByLastName(String lastName){
return employeeRepository.getByLastName(lastName);
}

@Transactional(readOnly=true)
public Page<Employee> getPage(int pageNo, int pageSize){
PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
return employeeRepository.findAll(pageable);
}
}


package com.htf.sssp.service;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.htf.sssp.entity.Department;
import com.htf.sssp.repository.DepartmentRepository;


@Service
public class DepartmentService {


@Autowired
private DepartmentRepository departmentRepository;

@Transactional(readOnly=true)
public List<Department> getAll(){
return departmentRepository.getAll();
}
}



剩下的就是添加Handerln  返回的jsp页面

WEB-INF 下的 view  之后添加jquery.js 


可参考源码,此处不再赘述。


将项目打包到TOMCAT 

启动tomcat  看到这个说明成功



打开google  输入 http://localhost:8080/sssp/


添加页面



列表页面



具体样式自己去改。


源码路径:http://download.csdn.net/download/a295277302/9829063


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值