`
TRAMP_ZZY
  • 浏览: 140203 次
社区版块
存档分类
最新评论

Spring 4.0.3+JPA(hibernate 4.3.5Final 实现)+Maven 配置文件入门实例

阅读更多

本案例是基于Spring 实现的JPA实例。JPA为SUN公司发布的ORM标准。是未来发展的趋势。Hibernate 已经率先支持。

1. Maven 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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>cn.bjfu</groupId>
	<artifactId>springdao</artifactId>
	<name>springdao</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.7</java-version>
		<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.1</org.slf4j-version>
		<jackson-version>1.9.0</jackson-version>
		<hibernate-version>4.3.5.Final</hibernate-version>
		<querydsl.version>2.9.0</querydsl.version>
	</properties>
	<dependencies>
		
		<!-- java mail -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>
		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1</version>
		</dependency>

		<!-- apache commons -->
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.5</version>
		</dependency>
		<!-- upload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.0.4</version>
		</dependency>
		
		<!-- validation -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.logging</groupId>
			<artifactId>jboss-logging</artifactId>
			<version>3.1.3.GA</version>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		
		<!-- hibernate  -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.1.0.Final</version>
		</dependency>
		
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-core</artifactId>
		    <version>${hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.common</groupId>
			<artifactId>hibernate-commons-annotations</artifactId>
			<version>4.0.4.Final</version>
		</dependency>

		<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-entitymanager</artifactId>
		    <version>${hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>antlr</groupId>
			<artifactId>antlr</artifactId>
			<version>2.7.7</version>
		</dependency>
		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
			<version>1.0</version>
		</dependency>
		<!-- <dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.1-api</artifactId>
			<version>1.0.0.Final</version>
		</dependency> -->

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>
		
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
	        <groupId>org.springframework.data</groupId>
	        <artifactId>spring-data-jpa</artifactId>
	        <version>1.6.0.RELEASE</version>
	    </dependency>
	    <dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons-core</artifactId>
			<version>1.4.1.RELEASE</version>
		</dependency>
	    
	    <!-- Querydsl -->
		
		<dependency>
			<groupId>com.mysema.querydsl</groupId>
			<artifactId>querydsl-jpa</artifactId>
			<version>${querydsl.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>hibernate-jpa-2.0-api</artifactId>
					<groupId>org.hibernate.javax.persistence</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- <dependency>
			<groupId>org.springframework.ws</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>1.5.10</version>
		</dependency>
		security 
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>3.1.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-acl</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-aspects</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-openid</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-asm</artifactId>
			<version>3.1.4.RELEASE</version>
		</dependency>
		-->
		<!-- cglib -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>
		
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		<dependency>
			<groupId>ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>1.2.3</version>
		</dependency>
		
		<!-- mysql-connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.24</version>
		</dependency>

		<!-- aspectjweaver -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.2</version>
		</dependency>

		<!-- jackson -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>${jackson-version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson-version}</version>
		</dependency>
		<!-- google gson -->
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.2.4</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.38</version>
		</dependency>
	
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>  
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- jacob -->
		<dependency>
			<groupId>net.sf.jacob-project</groupId>
			<artifactId>jacob</artifactId>
			<version>1.14.3</version>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2.1</version>
				<configuration>
					<mainClass>org.test.int1.Main</mainClass>
				</configuration>
			</plugin>
			<!-- 跳过测试代码 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<skip>true</skip>
					<testFailureIgnore>true</testFailureIgnore>
				</configuration>
			</plugin>
		</plugins>
		<finalName>springdao</finalName>
	</build>
</project>

2. root-context.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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:security="http://www.springframework.org/schema/security"
	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-3.1.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
	http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.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/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd">

	<!-- Root Context: defines shared resources visible to all other web components-->
	<context:component-scan base-package="cn.bjfu.springdao.jpa.dao.impl" />
	<context:component-scan base-package="cn.bjfu.springdao.jpa.service.impl" />
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 定义数据源Bean -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<!-- 连接数据库的驱动 -->
		<property name="driverClass" value="${jdbc.driverClass}"/>
		<!-- 连接数据库的url -->
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<!-- 数据库的账号 -->
		<property name="user" value="${jdbc.username}"/>
		<!-- 数据库的密码 -->
		<property name="password" value="${jdbc.password}"/>
		<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
		<property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
		<!-- 初始化连接池时连接的数量 -->
		<property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
		<!-- 连接池中保留的最小连接数 -->
		<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
		<!-- 连接池中保留的最大连接数  -->
		<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
		<!-- 控制数据源内加载的PreparedStatements数量 -->
		<property name="maxStatements" value="${c3p0.maxStatements}"/>
		<!-- 定义连接最大空闲时间,多长时间内连接未使用则连接被丢弃 -->
		<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
		<!-- 多长时间检查所有连接池中的空闲连接 -->
		<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
		<!-- 定义在从数据库获取新连接失败后重复尝试的次数 -->
		<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
		<!-- 获取连接失败后该数据源将申明已断开并永久关闭 -->
		<property name="breakAfterAcquireFailure" value="${c3p0.breakAfterAcquireFailure}"/>
		<!-- 每个connection提交的时候是否校验其有效性 -->
		<property name="testConnectionOnCheckout" value="${c3p0.testConnectionOnCheckout}"/>
	</bean>
	
	 <!-- This will ensure that Hibernate or JPA exceptions are automatically   
        translated into Spring's generic DataAccessException hierarchy for those   
        classes annotated with Repository. For example, see ***DAOImpl. -->  
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    
	 <!-- JPA实体管理工厂的配置 -->  
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">   
        <property name="dataSource" ref="dataSource"/>  
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>  
        <property name="packagesToScan" value="cn.bjfu.springdao.jpa.domain"/><!--待扫描的实体类包,不再需要persistence.xml了-->  
        <property name="jpaProperties">  
            <props>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.use_sql_comments">false</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>  
        </property>  
    </bean>
 	<jpa:repositories base-package="cn.bjfu.springdao.jpa.repository" entity-manager-factory-ref="entityManagerFactory" 
 		transaction-manager-ref="transactionManager" />
    <!--指定实现JPA的适配器-->  
    <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  
        <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />  
    </bean>  
      
    <!-- Jpa 事务配置 -->  
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">  
        <property name="entityManagerFactory" ref="entityManagerFactory"/>  
    </bean>  
    <!-- Spring Data Jpa配置 -->  
   
    <!-- 使用annotation定义事务 -->  
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  
  
    <!-- JSR303 Validator定义 -->  
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> 
</beans>

3. jdbc.properties
#Hibernate
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/docsearch?useUnicode=true&amp;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
c3p0.acquireIncrement=3
c3p0.initialPoolSize=2
c3p0.minPoolSize=1
c3p0.maxPoolSize=50
c3p0.maxStatements=0
c3p0.maxIdleTime=1800
c3p0.idleConnectionTestPeriod=1800
c3p0.acquireRetryAttempts=30
c3p0.breakAfterAcquireFailure=true
c3p0.testConnectionOnCheckout=false

#Mysql
#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost/jiningdb?useUnicode=true&amp;characterEncoding=UTF-8
#jdbc.username=root
#jdbc.password=root

4. 实体bean
package cn.bjfu.springdao.jpa.domain;  
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
 * Base class to derive entity classes from.
 * 
 * @author Oliver Gierke
 */
@MappedSuperclass
public class AbstractEntity {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	/**
	 * Returns the identifier of the entity.
	 * 
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/* 
	 * (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {

		if (this == obj) {
			return true;
		}

		if (this.id == null || obj == null || !(this.getClass().equals(obj.getClass()))) {
			return false;
		}

		AbstractEntity that = (AbstractEntity) obj;

		return this.id.equals(that.getId());
	}

	/* 
	 * (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		return id == null ? 0 : id.hashCode();
	}
	
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
package cn.bjfu.springdao.jpa.domain;  

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/** 
 * ClassName:Document <br/> 
 * Function: Document. <br/> 
 * Reason:   Document. <br/> 
 * Date:     2014年6月22日 下午4:07:36 <br/> 
 * @author   zhangzhaoyu 
 * @version   
 * @since    JDK 1.7 
 * @see       
 */
@Entity
@Table(name="document")
public class Document implements Serializable {
	/**
	 * serialVersionUID:TODO
	 * @since JDK 1.7
	 */
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name = "doc_id", nullable = false)
	private Integer docId;
	@Column(name = "doc_name", nullable = true)
	private String docName;
	@Column(name = "doc_type", nullable = true)
	private Byte docType;
	@Column(name = "add_datetime", nullable = true)
	private Date addDatetime;
	@Column(name = "modify_datetime", nullable = true)
	private Date modifyDatetime;
	@Column(name = "doc_location", nullable = true)
	private String docLocation;
	@Column(name = "upload_author", nullable = true)
	private String uploadAuthor;
	@Column(name = "author", nullable = true)
	private String anthor;
	
	public Document() {}

	public Integer getDocId() {
		return docId;
	}

	public void setDocId(Integer docId) {
		this.docId = docId;
	}

	public String getDocName() {
		return docName;
	}

	public void setDocName(String docName) {
		this.docName = docName;
	}

	public Byte getDocType() {
		return docType;
	}

	public void setDocType(Byte docType) {
		this.docType = docType;
	}

	public Date getAddDatetime() {
		return addDatetime;
	}

	public void setAddDatetime(Date addDatetime) {
		this.addDatetime = addDatetime;
	}

	public Date getModifyDatetime() {
		return modifyDatetime;
	}

	public void setModifyDatetime(Date modifyDatetime) {
		this.modifyDatetime = modifyDatetime;
	}

	public String getDocLocation() {
		return docLocation;
	}

	public void setDocLocation(String docLocation) {
		this.docLocation = docLocation;
	}

	public String getUploadAuthor() {
		return uploadAuthor;
	}

	public void setUploadAuthor(String uploadAuthor) {
		this.uploadAuthor = uploadAuthor;
	}

	public String getAnthor() {
		return anthor;
	}

	public void setAnthor(String anthor) {
		this.anthor = anthor;
	}

	@Override
	public String toString() {
		return "Document [docId=" + docId + ", docName=" + docName
				+ ", docType=" + docType + ", addDatetime=" + addDatetime
				+ ", modifyDatetime=" + modifyDatetime + ", docLocation="
				+ docLocation + ", uploadAuthor=" + uploadAuthor + ", anthor="
				+ anthor + "]";
	}
}
package cn.bjfu.springdao.jpa.domain;  

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/** 
 * ClassName:User <br/> 
 * Function: User. <br/> 
 * Reason:   User. <br/> 
 * Date:     2014年6月20日 下午3:10:21 <br/> 
 * @author   zhangzhaoyu 
 * @version   
 * @since    JDK 1.7 
 * @see       
 */
@Entity
@Table(name="user")
public class User implements Serializable {
	/**
	 * serialVersionUID:TODO
	 * @since JDK 1.7
	 */
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name = "user_id", nullable = false)
	private Integer userId;
	@Column(name = "name", nullable = false, length = 100)
	private String name;
	@Column(name = "password", nullable = true)
	private String password;
	@Column(name = "email", nullable = true)
	private String email;
	@Column(name = "add_datetime", nullable = true)
	private java.util.Date addDatetime;
	@Column(name = "edit_datetime", nullable = true)
	private java.util.Date editDatetime;
	
	public User() {}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getName() {
		return name;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

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

	public java.util.Date getAddDatetime() {
		return addDatetime;
	}

	public void setAddDatetime(java.util.Date addDatetime) {
		this.addDatetime = addDatetime;
	}

	public java.util.Date getEditDatetime() {
		return editDatetime;
	}

	public void setEditDatetime(java.util.Date editDatetime) {
		this.editDatetime = editDatetime;
	}

	@Override
	public String toString() {
		return "User [userId=" + userId + ", name=" + name + ", password="
				+ password + ", email=" + email + ", addDatetime="
				+ addDatetime + ", editDatetime=" + editDatetime + "]";
	}
}

5. 采用两种方式实现dao 层。
   一是继承Repository(有好几个类似接口)
   二是注入EntityManager
public interface UserDao {
	public abstract User findByName(String name);
	public abstract List<User> findAll();
	public abstract void saveOrUpdate(User user);
}
@Repository
public class UserDaoImpl implements UserDao {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public User findByName(String name) {
		TypedQuery<User> query = this.entityManager.createQuery("select u from User u where u.name = :name",
				User.class);
		query.setParameter("name", name);
		return query.getSingleResult();
	}

	@Override
	public List<User> findAll() {
		TypedQuery<User> query = this.entityManager.createQuery("select u from User u", User.class);
		return query.getResultList();
	}

	@Override
	public void saveOrUpdate(User user) {
			this.entityManager.persist(user);
	}
}

public interface DocumentRepository extends JpaRepository<Document, Integer> {

}


6. Service 实现
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface IDocumentService {
	Document findById(Integer docId);
	List<Document> findAll();
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface IUserService {
	public List<User> findAll();
}
@Service
public class DocumentService implements IDocumentService {

	@Autowired
	DocumentRepository documentRepository;
	
	@Override
	public Document findById(Integer docId) {
		return null;
	}

	@Override
	public List<Document> findAll() {
		return documentRepository.findAll();
	}

}
@Service
public class UserService implements IUserService {

	@Autowired
	private UserDao userDao;
	
	@Override
	@Transactional(readOnly = true)
	public List<User> findAll() {
		return this.userDao.findAll();
	}

}

7. web 层调用 controller
@Controller
public class HomeController {
	
	private static final Logger logger = Logger.getLogger(HomeController.class);
	@Autowired
	private IUserService userService;
	@Autowired
	private IDocumentService documentService;
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		List<User> list = userService.findAll();
		System.out.println(list);
		System.out.println("================================================================");
		List<Document> listDoc = documentService.findAll();
		for (Document doc : listDoc) {
			System.out.println(doc);
		}
		model.addAttribute("serverTime", formattedDate );
		return "home";
	}
	
}

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

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<!-- 下面标签内建的就是 FormattingConversionServiceFactoryBean 所以 Spring MVC 对处理方法的入参绑定就支持注解驱动的功能-->
	<mvc:annotation-driven />
	<context:component-scan base-package="cn.bjfu.springdao.web.controller" />
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory 
		 静态资源的处理 提供 rest 风格的URL 提供可能	cache-period 静态资源在客户浏览器的缓存时间-->
	<mvc:resources mapping="/resources/**" location="/resources/" cache-period="31536000"/>
	<!--
        - Message source for this context, loaded from localized "messages_xx" files.
        - Files are stored inside src/main/resources
    -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    	<property name="basename" value="messages/messages"/>
    </bean>

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<!-- CommonsMultipartResolver -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="1024000000"></property>
	</bean>
	
	<!-- Spring MVC HttpMessageConverter<T> 自定义之后则覆盖默认的值-->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters" ref="messageConverters" />
	</bean>
	默认配置以下四个
	<util:list id="messageConverters">
		<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
		<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
		<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
		<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
	</util:list> -->
	
	<!-- <bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
		<property name="streamDriver">
			<bean class="com.thoughtworks.xstream.io.xml.StaxDriver" />
		</property>
	</bean>
	
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	</bean> -->
	
	<!-- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="10" />
		<bean id="blogListExcel" class="cn.tramp.iblog.docview.BlogListExcelView" />
		<bean id="blogListPdf" class="cn.tramp.iblog.docview.BlogListPdfView" />
		<bean id="userListExcel" class="cn.tramp.iblog.docview.UserListExcelView" />
	<bean id="userListPdf" class="cn.tramp.iblog.docview.UserListPdfView" /> -->
</beans>

9. 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_3_0.xsd" id="WebApp_ID" version="3.0">
 
	<display-name>springdao</display-name>
	<description>springdao</description>
	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<!-- 多个配置文件使用逗号分隔 -->
	<!--<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/root-context.xml, classpath:spring/applicationContext-security.xml</param-value>
	</context-param>-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/root-context.xml</param-value>
	</context-param>
	<!-- log4j -->
	<context-param>  
	    <param-name>log4jConfigLocation</param-name>  
	    <param-value>classpath:log4j.properties</param-value>  
	</context-param>  

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- spring 内存监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<!-- Processes application requests -->
	
	<!-- spring securit start 
		Spring Security 实际上是使用多个过滤器形成的链条来工作的。
	
    <filter> 
      <filter-name>springSecurityFilterChain</filter-name> 
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
    </filter> 
    <filter-mapping> 
      <filter-name>springSecurityFilterChain</filter-name> 
      <url-pattern>/*</url-pattern> 
    </filter-mapping> --> 
    <!-- spring securit start --> 
    
	<!-- 初始化 WebApplicationContext  -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter>
	    <filter-name>encodingFilter</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>
	    <init-param>
	      <param-name>forceEncoding</param-name>
	      <param-value>true</param-value>
	    </init-param>
	</filter>
	  
	<filter-mapping>
	   <filter-name>encodingFilter</filter-name>
	   <url-pattern>/*</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
	
	<!-- session outtime 15 min -->
	<!-- <session-config>
		<session-timeout>15</session-timeout>
	</session-config> -->
</web-app>


注意事项

1. <jpa:repositories/> 方式时,需要引入http://www.springframework.org/schema/data/repository
2. 注意Maven 引入的爆冲突解决。
分享到:
评论

相关推荐

    Spring 4.0.6+Hibernate 4.3.5 + Jpa+DBCP2

    1. 添加依赖:在项目中引入Spring、Hibernate、JPA和DBCP2的相关库文件,例如lib-spring 4.0.6、Hibernate 4.3.5和JPA的依赖。 2. 配置数据源:在Spring的配置文件中,使用DBCP2的数据源bean,设置数据库连接参数如...

    springMVC(4.0.3.RELEASE) + hibernate(4.3.5.Final) + CXF(2.6.8)+ mysql + jquery

    本项目结合springMVC(4.0.3.RELEASE) + spring + hibernate(4.3.5.Final) + CXF(2.6.8)+ mysql + jquery等技术,并以Maven形式实现。具体包含以下主要功能点: 1.用CXF实现Webservice和Restful服务 2.分别使用...

    ssh整合最新demostruts2.3+spring4.0.3+hibernate4.3.4

    3,struts版本:struts-2.3.16.1 spring版本:spring-framework-4.0.3.RELEASE hibernate版本:hibernate-release-4.3.4.Final 4,集成了编码过滤器和压缩过滤器,拿来就可以直接在上面建新工程。

    spring4.0+hibernate4.2

    综上所述,"spring4.0+hibernate4.2+struts2实现增删改功能"意味着项目利用这三个框架协同工作,实现了一套完整的Web应用。Spring管理依赖注入和业务流程,Hibernate处理数据持久化,而Struts2则作为前端控制器,...

    Spring4 MVC Hibernate4集成(Annotation)

    Spring4 MVC Hibernate4集成,使用Annotation,封装dao层和service层。 环境: spring 4.0.3.RELEASE hibernate 4.3.5.Final mysql 5.1.29

    Spring4.0.3jar包及文档

    Spring框架是Java开发中最受欢迎的轻量级框架之一,它为构建企业级应用程序提供了全面的编程和配置模型。Spring4.0.3是该框架的一个重要版本,它引入了许多改进和新特性,以提高开发效率和应用性能。下面将详细讨论...

    spring 4.0.3

    6. **JDBC与ORM改进**:Spring Data项目在4.0.3中进一步优化了对JDBC和ORM框架(如Hibernate、JPA)的支持,提供了更强大的数据访问抽象,降低了数据层的复杂性。 7. **MVC增强**:Spring MVC在4.0.3中增强了模型-...

    超级截图 (Android 4.0.3+).apk

    超级截图 (Android 4.0.3+).apk

    Sketchbook-v4.0.0 (Android 4.0.3+).apk

    Sketchbook-v4.0.0 (Android 4.0.3+).apk

    linuxdeploy-2.4.1-252 (Android 4.0.3+).apk.cab

    linuxdeploy-2.4.1-252 (Android 4.0.3+).apk.cab

    云端媒体 v3.9.1(Android4.0.3+).apk

    云端媒体 v3.9.1(Android4.0.3+).apk 手机端利器

    SpringMVC4.0.3+Mybatis3.2.5+EasyUI1.4.1 Demo

    该项目使用springmvc4.0.3 + Mybatis3.2.5 前端使用easyUI1.4.1 该项目示例有: 1.ajax请求,返回JSON数据,有中文乱码解决方案 2.登陆拦截,未登陆过的用户将跳转到登陆页面 3.邮件发送 4.企业级前端界面 5.前端...

    spring-core-4.0.3.RELEASE.jar (spring 4.0.3核心jar包)

    spring-core-4.0.3.RELEASE.jar (spring 4.0.3核心jar包),Java开发中spring框架开发必须的依赖包。

    Struts+Spring+Hibernate配置说明

    #### 四、工程文件配置 **1. 创建工程** - 在Eclipse中通过File&gt;New&gt;Project...创建新的Java Web项目。 - 配置项目的基本信息,如项目名称、位置等。 **2. 配置工程** - **版本控制集成**:通过Eclipse中的Team...

    Wechat6.3.31smali第二版

    在本案例中,"Wechat6.3.31smali"是一个已经反编译完成的微信版本,它的每个.smali文件对应了原始的Java类文件,提供了一个深入研究微信内部结构的窗口。 在描述中提到的“smali断点”是逆向工程中的一个重要概念。...

    springMVC+hibernate+spring4.3 jar包整合

    4. 配置Hibernate:在Hibernate配置文件(hibernate.cfg.xml)中设置数据库连接信息,定义实体类和对应的映射文件,或者使用注解进行ORM配置。 5. 实现业务逻辑:在Service层使用Spring的依赖注入获取...

    Spring4 MVC 集成Hibernate4源码下载

    Spring4.0.3,Hibernate4.3.5,mysql。 需要创建users表 DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `age` int(11) DEFAULT NULL, `nice_name` varchar(32) ...

    spring-core-4.0.3.RELEASE-sources.jar (spring 4.0.3源码source)

    spring-core-4.0.3.RELEASE-sources.jar (spring 4.0.3源码source),导入到Eclipse中进行查看。

    配置Struts+Spring+Hibernate 开发环境详解

    #### 三、工程文件配置 1. **创建新工程**: - 通过`File &gt; New &gt; Project...`创建一个新的Web项目。 - 设置项目名称、构建类型等信息。 2. **配置工程**: - 使用`Team &gt; Get Latest Version`获取最新版本的...

    Struts+Spring+Hibernate 开发环境.doc

    #### 工程文件配置 **1. 创建项目** 1. 在 Eclipse 中通过 File &gt; New &gt; Project… 创建新的 Java Web 项目。 **2. 配置工程** 1. 使用 Team &gt; Get Latest Version 选项获取最新版本的工程文件。 2. 使用 Team &gt;...

Global site tag (gtag.js) - Google Analytics