当前位置: 代码迷 >> JavaScript >> spring3.0+hibernate3.6+jpa2.0+maven+jsf2.0 调整示例
  详细解决方案

spring3.0+hibernate3.6+jpa2.0+maven+jsf2.0 调整示例

热度:762   发布时间:2012-12-28 10:29:04.0
spring3.0+hibernate3.6+jpa2.0+maven+jsf2.0 整合示例
maven配置文件pom.xml:
<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>com.chinaforwards.niagara</groupId>
	<artifactId>ibms</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>IBMS</name>
	<url>http://ba.chinaforwards.com</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.0.Final</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.8.0.GA</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.6.0.Final</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-commons-annotations</artifactId>
			<version>3.2.0.Final</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.1</version>
				<configuration>
					<server>tomcat</server>
					<path>/</path>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<wtpversion>2.0</wtpversion>
					<additionalProjectFacets>
						<jst.jsf>2.0</jst.jsf>
						<wst.jsdt.web>1.0</wst.jsdt.web>
						<jpt.jpa>2.0</jpt.jpa>
						>
					</additionalProjectFacets>
					<additionalConfig>
						<file>
							<name>.settings/org.eclipse.jpt.core.prefs</name>
							<location>eclipse/.settings/org.eclipse.jpt.core.prefs</location>
						</file>
					</additionalConfig>
					<sourceExcludes>
						<sourceExclude>**/.svn/</sourceExclude>
					</sourceExcludes>
					<downloadJavadocs>true</downloadJavadocs>
					<downloadSources>true</downloadSources>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


jpa的配置,persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
	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_2_0.xsd">
	<persistence-unit name="ems">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<class>com.chinaforwards.niagara.ems.jpa.Person</class>
		<class>com.chinaforwards.niagara.ems.jpa.Event</class>
		<properties>
			<property name="hibernate.connection.driver_class" value="net.sourceforge.jtds.jdbc.Driver" />
			<property name="hibernate.connection.url" value="jdbc:jtds:sqlserver://localhost:1433/test" />
			<property name="hibernate.connection.username" value="sa" />
			<property name="hibernate.connection.password" value="" />
			<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
			<property name="hibernate.cache.use_query_cache" value="false" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.useUnicode" value="true" />
			<property name="hibernate.characterEncoding" value="utf8" />
			<property name="hibernate.hbm2ddl.auto" value="create" />
		</properties>
	</persistence-unit>
</persistence>


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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
	<display-name>ROOT</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/ApplicationContext.xml</param-value>
	</context-param>
	<filter>
		<display-name>AuthFilter</display-name>
		<filter-name>AuthFilter</filter-name>
		<filter-class>com.chinaforwards.niagara.web.AuthFilter</filter-class>
		<init-param>
			<param-name>excludes</param-name>
			<param-value>^/login.*;^/images/.*;^/styles/.*;.*\.xhtml</param-value>
		</init-param>
	<servlet>
		<description></description>
		<display-name>HibernateTestServlet</display-name>
		<servlet-name>HibernateTestServlet</servlet-name>
		<servlet-class>com.chinaforwards.niagara.web.test.HibernateTestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HibernateTestServlet</servlet-name>
		<url-pattern>/HibernateTestServlet</url-pattern>
	</servlet-mapping>
</web-app>


ApplicationContxt.xml:
<?xml  version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context  
	   http://www.springframework.org/schema/context/spring-context-3.0.xsd  
	   http://www.springframework.org/schema/tx  
	   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
	   http://www.springframework.org/schema/aop  
	   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  

	<context:component-scan base-package="com.chinaforwards.niagara.web.test" />       <!-- 扫描规则 -->
	
	<tx:annotation-driven transaction-manager="transactionManager" />

	<import resource="jpa.xml" />

</beans>


jpa.xml:
<?xml  version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context  
       http://www.springframework.org/schema/context/spring-context-3.0.xsd  
       http://www.springframework.org/schema/tx  
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
       http://www.springframework.org/schema/aop  
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="ems" />
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
</beans>


实体类的简单参考,person中有一些event,一对多的关系
Event.java:
package com.chinaforwards.niagara.ems.jpa;

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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.UniqueConstraint;

@Entity
public class Event implements Serializable {

	private static final long serialVersionUID = 1L;
    private long id;
    private String title;
    private Date date;
    private Person person;
    
    @Id
    @GeneratedValue
    public long getId() {
    
        return this.id;
    }
    
    public void setId(long id) {
    
        this.id = id;
    }
    
    public String getTitle() {
    
        return this.title;
    }
    
    @ManyToOne
    @JoinTable(
        name="person_event",
        joinColumns=@JoinColumn(name="e_id"),
        inverseJoinColumns=@JoinColumn(name="p_id"),
        uniqueConstraints=@UniqueConstraint(columnNames={"p_id"})
    )
    public Person getPerson() {
    
        return person;
    }
    
    public void setPerson(Person person) {
    
        this.person = person;
        if(person.getEvents()!=null){
            person.getEvents().add(this);
        }else{
            HashSet<Event> set = new HashSet<Event>();
            set.add(this);
            person.setEvents(set);
        }
    }

    public void setTitle(String title) {
    
        this.title = title;
    }
    
    public Date getDate() {
    
        return this.date;
    }
    
    public void setDate(Date date) {
    
        this.date = date;
    }
   
}


Person.java:
package com.chinaforwards.niagara.ems.jpa;

import java.io.Serializable;
import java.util.Date;
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;
import javax.persistence.Transient;

@Entity
@Table(name="person")
public class Person implements Serializable {

    private long id;
    private String name;
    private int age;
    private Date birthday;
    private int sex;
    private Set<Event> events;
    private static final long serialVersionUID = 1L;
    
    @OneToMany(cascade=CascadeType.ALL,mappedBy="person")
    public Set<Event> getEvents() {
    
        return this.events;
    }

    public void setEvents(Set<Event> events) {
    
        this.events = events;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public long getId() {

        return this.id;
    }

    public void setId(long id) {

        this.id = id;
    }

    @Column(length=10)
    public String getName() {

        return this.name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public int getAge() {

        return this.age;
    }

    public void setAge(int age) {

        this.age = age;
    }

    public Date getBirthday() {

        return this.birthday;
    }

    public void setBirthday(Date birthday) {

        this.birthday = birthday;
    }
    
    @Transient
    public int getSex() {
    
        return this.sex;
    }

    public void setSex(int sex) {
    
        this.sex = sex;
    }

}


配置大致就是这样,下面看下简单的dao层,利用spring自动的事务机制:
TestDao.java:
package com.chinaforwards.niagara.web.test;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional     
@Service("service") 
public class TestDao implements IDao{
    
    @PersistenceContext
    EntityManager em; 
    
    @Transactional(propagation = Propagation.REQUIRED)
    public void save(Object o){
        
        em.persist(o);
//        throw new RuntimeException("niub");
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    public Object get(Class c, Object k){
        
        return em.find(c, k);
    }
}


简单的使用方法:
HibernateTestServlet.java:
package com.chinaforwards.niagara.web.test;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.chinaforwards.niagara.ems.jpa.Event;
import com.chinaforwards.niagara.ems.jpa.Person;

/**
 * Servlet implementation class HibernateTestServlet
 */
public class HibernateTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HibernateTestServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    ServletContext servletContext = this.getServletContext();   
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);   
        IDao dao = (IDao)ctx.getBean("service");  
        Person p = new Person();
        p.setName("ggg");
        p.setBirthday(new Date(System.currentTimeMillis()));
        p.setAge(22);
        p.setSex(0);
        Event e = new Event();
        e.setDate(new Date(System.currentTimeMillis()));
        e.setTitle("cvv");
        e.setPerson(p);
        try {
            dao.save(p);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        
        Person p2 = (Person) dao.get(Person.class, p.getId());
        System.out.println(p2.getEvents() == null);//false
        
        Event e2 = (Event) dao.get(Event.class, e.getId());
        System.out.println(e2.getPerson() == null);//false
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


接下来加入jsf的整合
faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>

<faces-config 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-facesconfig_2_0.xsd"
	version="2.0">

	<application>
		<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
	</application>

	<navigation-rule>
		<from-view-id>/index.xhtml</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/test.xhtml</to-view-id>
		</navigation-case>
		<navigation-case>
			<from-outcome>failure</from-outcome>
			<to-view-id>/index.xhtml</to-view-id>
		</navigation-case>
	</navigation-rule>

	<managed-bean>
		<managed-bean-name>user</managed-bean-name>
		<managed-bean-class>com.chinaforwards.niagara.web.test.User</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
		<managed-property>
			<property-name>dao</property-name>
			<value>#{service}</value>
		</managed-property>
	</managed-bean>
</faces-config>


web.xml中加入jsf的支持:
<servlet>
		<servlet-name>FacesServlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>0</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>FacesServlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>


jsf的管理bean:
package com.chinaforwards.niagara.web.test;

import java.util.Date;

import com.chinaforwards.niagara.ems.jpa.Event;
import com.chinaforwards.niagara.ems.jpa.Person;

public class User {
    
    private String name;
    private IDao dao;
    public String login(){
        
        String ret = "";
        if("qygeng".equals(name)){
            Person p = new Person();
            p.setName("qygeng");
            p.setBirthday(new Date(System.currentTimeMillis()));
            p.setAge(22);
            p.setSex(0);
            Event e = new Event();
            e.setDate(new Date(System.currentTimeMillis()));
            e.setTitle("admin");
            e.setPerson(p);
            try {
                dao.save(p);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            ret = "success";
        }else{
            ret = "failure";
        }
        return ret;
    }
    
    public String getName() {
    
        return this.name;
    }
    
    public void setName(String name) {
    
        this.name = name;
    }
    
    public IDao getDao() {
    
        return this.dao;
    }
    public void setDao(IDao dao) {
    
        this.dao = dao;
    }
}


最后,就是页面的编写:
<?xml version="1.0" encoding="UTF-8" ?>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<body>
<f:view>
	<h:form>
		<h3>请输入您的名称</h3>
		名称: <h:inputText value="#{user.name}" />
		<h:commandButton value="送出" action="#{user.login}" />
	</h:form>
</f:view>
</body>
</html>
  相关解决方案