primefaces教程_Primefaces Spring和Hibernate集成示例教程

primefaces教程

Welcome to the Spring Primefaces and Hibernate Integration example. Integration between frameworks is a complex mission and mostly it needs a lot of time to achieve. We’ve discussed a Primefaces, Spring and Hibernate frameworks in a separate tutorials, but this time we will show you how can integrate all of them to create a layered (tiered) application.

欢迎使用Spring Primefaces和Hibernate集成示例。 框架之间的集成是一项复杂的任务,并且通常需要很多时间才能实现。 我们已经在单独的教程中讨论了PrimefacesSpringHibernate框架,但是这次我们将向您展示如何集成所有框架以创建分层(分层)应用程序。

SpringPrimefacesHibernate (Spring Primefaces Hibernate)

Layered (tiered) application is a popular design that most of the enterprise applications are aligned with. In which:

分层(分层)应用程序是一种流行的设计,大多数企业应用程序都与之保持一致。 其中:

  1. Primefaces framework will be used for handling all UI concerns and verify client’s inputs.

    Primefaces框架将用于处理所有UI问题并验证客户的输入。
  2. Hibernate framework will be used for communicating your own persistence store that probably is a MySQL database.

    Hibernate框架将用于传达您自己的持久性存储,该存储可能是MySQL数据库。
  3. Spring framework will be used to glue between all of these frameworks.

    Spring框架将用于粘合所有这些框架。

This tutorial intended for implementing a layered application using all of these listed frameworks.

本教程旨在使用所有列出的框架来实现分层的应用程序。

Spring Primefaces Hibernate所需工具 (Spring Primefaces Hibernate Required Tools)

Before getting started delve into, let’s see the required tools that you would need for:

在开始深入研究之前,让我们看一下所需的必需工具:

  • Eclipse Kepler 4.3.

    Eclipse开普勒4.3。
  • Hibernate 3.x.

    Hibernate3.x。
  • Spring 4.x.

    春天4.x.
  • Primefaces 5.x.

    Primefaces5.x。
  • JDK 1.6+.

    JDK 1.6以上版本。
  • MySQL 5.x.

    MySQL5.x。

Primefaces Spring Hibernate项目结构 (Primefaces Spring Hibernate Project Structure)

Our final project structure will look like below image, we will go through each of the components one by one.

我们的最终项目结构将如下图所示,我们将逐一介绍每个组件。

创建数据库员工表 (Create Database Employee Table)

MySQL database would be used for retaining all of employees instances/records. Used Employee Table looks like below:

MySQL数据库将用于保留所有员工实例/记录。 已用员工表如下所示:

Also, find below its SQL create-script:

另外,在其SQL创建脚本下方找到:

CREATE TABLE `employee` (
  `EMP_ID` int(11) NOT NULL AUTO_INCREMENT,
  `EMP_NAME` varchar(45) DEFAULT NULL,
  `EMP_HIRE_DATE` datetime DEFAULT NULL,
  `EMP_SALARY` decimal(11,4) DEFAULT NULL,
  PRIMARY KEY (`EMP_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

创建员工模型Bean (Create Employee Model Bean)

After we created an Employee Table, it’s a proper time to get a look at how Employee class would look like:

创建Employee Table之后,现在是时候看看Employee类的样子了:

package com.journaldev.hibernate.data;

import java.util.Date;

public class Employee {
	private long employeeId;
	private String employeeName;
	private Date employeeHireDate;
	private double employeeSalary;

	public long getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(long employeeId) {
		this.employeeId = employeeId;
	}

	public String getEmployeeName() {
		return employeeName;
	}

	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public Date getEmployeeHireDate() {
		return employeeHireDate;
	}

	public void setEmployeeHireDate(Date employeeHireDate) {
		this.employeeHireDate = employeeHireDate;
	}

	public double getEmployeeSalary() {
		return employeeSalary;
	}

	public void setEmployeeSalary(double employeeSalary) {
		this.employeeSalary = employeeSalary;
	}
}

Spring PrimefacesHibernateMaven依赖关系 (Spring Primefaces Hibernate Maven Dependencies)

Maven is a build tool, it’s used mainly for managing project dependencies. So no need for downloading JARs and appending them into your project as you did normally. MySQL JDBC driver, hibernate core, Spring core framework, Primefaces and many libraries that we need for Spring Hibernate Primefaces integration. Our final pom.xml file looks like below.

Maven是一个构建工具,主要用于管理项目依赖项。 因此,无需像通常那样下载JAR并将其附加到项目中。 MySQL JDBC驱动程序Hibernate核心Spring核心框架Primefaces以及我们进行Spring Hibernate Primefaces集成所需的许多库。 我们最终的pom.xml文件如下所示。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.journaldev</groupId>
	<artifactId>Primefaces-Hibernate-Spring-Integration-Sample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Primefaces-Hibernate-Spring-Integration-Sample Maven Webapp</name>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<url>https://maven.apache.org</url>
	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>https://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>
	<dependencies>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<!-- Faces Implementation -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.2.4</version>
		</dependency>
		<!-- Faces Library -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.2.4</version>
		</dependency>
		<!-- Primefaces Version 5 -->
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>5.0</version>
		</dependency>
		<!-- JSP Library -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!-- JSTL Library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>
		<!-- Primefaces Theme Library -->
		<dependency>
			<groupId>org.primefaces.themes</groupId>
			<artifactId>blitzer</artifactId>
			<version>1.0.10</version>
		</dependency>
		<!-- Hibernate library -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.10.Final</version>
		</dependency>
		<!-- MySQL driver connector library -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.31</version>
		</dependency>
		<!-- Spring ORM -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<!-- Spring Web -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<!-- Required By Hibernate -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.12.1.GA</version>
		</dependency>
	</dependencies>
</project>

Spring Primefaces –Hibernate配置 (Spring Primefaces – Hibernate Configuration)

Hibernate is a standard Object Relational Mapping (ORM) solution, it’s used for mapping your object domain into relational tabular formula. Hibernate configuration process require below steps:

Hibernate是一个标准的对象关系映射(ORM)解决方案,用于将您的对象域映射到关系表格式中。 Hibernate配置过程需要执行以下步骤:

  • Specify all relevant database information like driver, JDBC URL, hibernate dialect and hibernate session context in a hibernate configuration file, mainly using hibernate.cfg.xml. Dialect will be used by hibernate implementation itself for make sure the execution of mapping process is done effectively. This file should be located under project’s src/main/resources folder.

    主要在hibernate配置文件中指定所有相关的数据库信息,例如驱动程序,JDBC URL,hibernate方言和hibernate会话上下文,主要使用hibernate.cfg.xml 。 Hibernate实现本身将使用方言来确保映射过程的执行有效完成。 该文件应位于项目的src / main / resources文件夹下。
  • Specify hibernate’s mapping file. Mapping file will contains all of mapping information, like objects-tables, attributes-columns and associations-relations, domain-classes.hbm.xml file is mainly used for this purpose. This file should be located under project’s src/main/resources folder so that it’s in the classpath of the application.

    指定Hibernate的映射文件。 映射文件将包含所有映射信息,例如对象表,属性列和关联关系, domain-classes.hbm.xml文件主要用于此目的。 该文件应位于项目的src / main / resources文件夹下,以便位于应用程序的类路径中。
  • It’s important to say that some of modifications would be required when we’re going to use Spring.

    重要的是要说,当我们要使用Spring时,需要进行一些修改。

hibernate.cfg.xml

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/journaldev</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Specify session context -->
        <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
        <!-- Show SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- Referring Mapping File -->
        <mapping resource="domain-classes.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

domain-classes.hbm.xml

domain-classes.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"https://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
	<class name="com.journaldev.hibernate.data.Employee" table="employee">
		<id name="employeeId" column="EMP_ID" type="long">
			<generator class="native" />
		</id>
		<property name="employeeName" column="EMP_NAME" type="string"/>
		<property name="employeeHireDate" column="EMP_HIRE_DATE" type="date"/>
		<property name="employeeSalary" column="EMP_SALARY" type="double"/>
	</class>
</hibernate-mapping>

测试我们的Hibernate应用程序 (Test our Hibernate Application)

Till now, we’ve created an Eclipse Web project configured with required dependencies, created database Employee Table and created hibernate framework accompanies.

到目前为止,我们已经创建了一个使用必需的依赖项进行配置的Eclipse Web项目,创建了数据库Employee Table,并创建了Hibernate框架。

Before going far away with Spring integration and developing a Primefaces UI form, let’s see how can we use a simple Java Application for getting Employee instance saved against our own database. Given Java Application would help us identifying the benefits we’ll get especially when it comes to use a Spring framework later on.

在继续进行Spring集成和开发Primefaces UI表单之前,让我们看看如何使用简单的Java应用程序将Employee实例保存到我们自己的数据库中。 给定的Java应用程序将帮助我们确定我们将获得的好处,尤其是稍后使用Spring框架时。

package com.journaldev;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.journaldev.hibernate.data.Employee;

public class Main {
	public static void main(String [] args){
		// Create a configuration instance
		Configuration configuration = new Configuration();
		// Provide configuration file
		configuration.configure("hibernate.cfg.xml");
		// Build a SessionFactory
		SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
		// Get current session, current session is already associated with Thread
		Session session = factory.getCurrentSession();
		// Begin transaction, if you would like save your instances, your calling of save must be associated with a transaction
		session.getTransaction().begin();
		// Create employee
		Employee emp = new Employee();
		emp.setEmployeeName("Peter Jousha");
		emp.setEmployeeSalary(2000);
		emp.setEmployeeHireDate(new Date());
		// Save
		session.save(emp);
		// Commit, calling of commit will cause save an instance of employee
		session.getTransaction().commit();
	}
}

Here’s detailed clarifications for the above code:

以下是上述代码的详细说明:

  • Hibernate requires a defined context for make your acquired session affected. Standard Java Application context can be achieved by providing hibernate’s attribute hibernate.current_session_context_class. Value of org.hibernate.context.internal.ThreadLocalSessionContext will be binded the context to the current executed thread. That’s mean, if you’ve invoked any type of CRUD operations against session object within an active Transaction, they will be executing into your own database once the Transaction has committed. In our case, an new employee instance has been saved. If you’ve used hibernate 3, this property should be thread instead of using ThreadLocalSessionContext.

    Hibernate需要定义的上下文,以使您获得的会话受到影响。 通过提供hibernate的属性hibernate.current_session_context_class可以实现标准Java应用程序上下文。 org.hibernate.context.internal.ThreadLocalSessionContext的值将把上下文绑定到当前执行的线程。 这意味着,如果您对活动事务中的会话对象调用了任何类型的CRUD操作,则一旦事务提交,它们将在您自己的数据库中执行。 在我们的例子中,新的员工实例已保存。 如果您使用过Hibernate3,则此属性应为thread而不是ThreadLocalSessionContext。
  • Hibernate 4 is used for Testing purpose, this version of hibernate isn’t applicable when it comes to integrate with Spring 4. To integrate with Spring 4, you’ve requested to use Hibernate 3.

    Hibernate 4用于测试目的,此版本的hibernate在与Spring 4集成时不适用。要与Spring 4集成,您已请求使用Hibernate 3。
  • Using of latest version of hibernate requires you to use StandardServiceRegistryBuilder to build SessionFactory.

    使用最新版本的hibernate要求您使用StandardServiceRegistryBuilder来构建SessionFactory。

设置弹簧 (Setting Up Spring)

Spring is a comprehensive framework, it’s used mainly for Inversion of Control (IoC) which consider the more general category of the well-known concept Dependency Injection.

Spring是一个全面的框架,主要用于控制反转(IoC),它考虑了众所周知的概念Dependency Injection的更一般的类别。

However, a provided simple Java Application keep you capable of getting your Employee instances saved against your own database, but typically, this isn’t the way that most of applications use to configure their own hibernate persistence layer.

但是,提供的简单Java应用程序使您能够将Employee实例保存到自己的数据库中,但是通常,这不是大多数应用程序用来配置其自己的Hibernate持久层的方式。

Using of Spring will help you avoiding all creating and associating objects stuffs. Creating required objects, associating others are mainly a Spring job. Following are Spring context configuration file, updated hibernate configuration, updated Maven pom.xml and our deployment descriptor file. Let’s see how can we configure all of these to make a proper use of Spring.

使用Spring将帮助您避免所有创建和关联对象的东西。 创建所需的对象,关联其他对象主要是Spring的工作。 以下是Spring上下文配置文件,更新的Hibernate配置,更新的Maven pom.xml和我们的部署描述符文件。 让我们看看如何配置所有这些以正确使用Spring。

applicationContext.xml

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:tx="https://www.springframework.org/schema/tx"
	xmlns:context="https://www.springframework.org/schema/context"
	xmlns:aop="https://www.springframework.org/schema/aop" xmlns:util="https://www.springframework.org/schema/util"
	xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd https://www.springframework.org/schema/context  https://www.springframework.org/schema/context/spring-context-3.2.xsd https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
	<!-- Enable Spring Annotation Configuration -->
	<context:annotation-config />
	<!-- Scan for all of Spring components such as Spring Service -->
	<context:component-scan base-package="com.journaldev.spring.service"></context:component-scan>
	<!-- Create Data Source bean -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/journaldev" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
	<!-- Define SessionFactory bean -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>domain-classes.hbm.xml</value>
			</list>
		</property>
		<property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
	</bean>
	<!-- Transaction Manager -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- Detect @Transactional Annotation -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

hibernate.cfg.xml

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>

web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
	https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5" metadata-complete="true">
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>
	<context-param>
		<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
	</listener>
</web-app>

Here’s detailed explanation for the code given above:

这是上面给出的代码的详细说明:

  • We’ve created a SessionFactory by instantiating a Spring Bean called sessionFactory. Instantiating of SessionFactory does require passing an instant of data source instance, passing mapping files (domain-classes.hbm.xml as is), passing all required Hibernate properties via using of hibernate.cfg.xml. As you’ve noticed, hibernate.cfg.xml doesn’t contain database information, cause it’s defined instantly – Data Source Bean – and no need for hibernate session context, cause it’s enriched by Apache Tomcat. Even Apache Tomact isn’t a managed server, but it contains facilities that make help create a contextual session.

    我们通过实例化一个称为sessionFactory的Spring Bean创建了一个SessionFactory。 实例化SessionFactory确实需要传递数据源实例的实例,传递映射文件(按原样提供domain-classes.hbm.xml),通过使用hibernate.cfg.xml传递所有必需的Hibernate属性。 正如您所注意到的,hibernate.cfg.xml不包含数据库信息,因为它是立即定义的- 数据源Bean-不需要Hibernate会话上下文,因此可以被Apache Tomcat丰富。 甚至Apache Tomact也不是托管服务器,但它包含有助于创建上下文会话的功能。
  • Transaction Manager will help you eliminate using a snippet of code like session.getTransaction().begin() and commit(). @Transactional annotation will be used alternatively. That’s mean, executing of any Spring Service’s methods annotated with @Transactional will be done in a Transnational manner. In case you’ve called a CRUD operation against your session within a Transnational scope like session.save(), it will be executing directly into your own database at the end of called method. That’s called Transaction Demarcation.

    事务管理器将帮助您消除使用诸如session.getTransaction()。begin()commit()之类的代码片段。 @Transactional注释将替代使用。 这就是说,任何以@Transactional注释的Spring Service方法的执行都将以跨国方式完成。 如果您在跨国范围内(例如session.save())会话调用了CRUD操作,它将在被调用方法的结尾直接在您自己的数据库中执行。 这就是所谓的事务划分。
  • You can define your own Spring Services by using @Component. That will be scanned automatically.

    您可以使用@Component定义自己的Spring Services。 那将被自动扫描。
  • A new libraries are added into our pom.xml maven dependencies file, common-dbcp and javassist  are required by hibernate 3. If you’ve noticed, these libraries aren’t required for Hibernate 4.

    一个新的库被添加到我们的pom.xml maven依赖文件中,Hibernate3要求common-dbcpjavassist 。如果您已经注意到,Hibernate4则不需要这些库。
  • It’s mandatory to add Spring context loader listener for your web.xml file. This listener required an applicationContext.xml to be defined underneath of WEB-INF/ folder. This is the default location and name for Spring configuration context file. In case you would to change its location and name you must add below snippet of code provided with required path.

    必须为web.xml文件添加Spring上下文加载器侦听器。 该侦听器要求在WEB-INF /文件夹下定义一个applicationContext.xml 。 这是Spring配置上下文文件的默认位置和名称。 万一您要更改其位置和名称,必须在以下带有所需路径的代码段中添加。

Configure non-default Spring Context Location:

配置非默认的Spring上下文位置:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/SpringContext.xml</param-value>
    </context-param>

NOTE: If you are looking for Spring 4 and Hibernate 4 integration, we need to make some small changes in the Spring Bean configuration file, you can get more details about that at Spring Hibernate Integration Example.

注意 :如果您正在寻找Spring 4和Hibernate 4的集成,我们需要在Spring Bean配置文件中进行一些小的更改,您可以在Spring Hibernate Integration Example中获得有关此配置的更多详细信息。

Spring员工服务 (Spring EmployeeService)

In a layered application like what we’re doing here, all of business operations must be achieved by services. Spring provides you ability to define your own services that would contain your own business rules. EmployeeService would contain the required business for create an Employee.

在像我们在此所做的分层应用程序中,所有业务操作都必须通过服务来实现。 Spring提供了定义包含业务规则的服务的能力。 EmployeeService将包含创建Employee所需的业务。

package com.journaldev.spring.service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.hibernate.data.Employee;

@Component
public class EmployeeService {
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional
	public void register(Employee emp){
		// Acquire session
		Session session = sessionFactory.getCurrentSession();
		// Save employee, saving behavior get done in a transactional manner
		session.save(emp);
	}
}

Here’s detailed explanation for the above code:

以下是上述代码的详细说明:

  • EmployeeService is a Spring service, @Component annotation is used for defining Spring Service. By default, Spring will scan your mentioned package(s) for locating your service based on context:component-scan Tag.

    EmployeeService是一个Spring服务,@ Component批注用于定义Spring Service。 默认情况下,Spring将根据上下文扫描您提到的软件包以查找服务:component-scan   标签。
  • @Autowired will help you get required instances injected. That’s Dependency Injection or IoC (Inversion of Control) concept. It’s important concept, it means that instead of allowing the developer controlling the process of creating instances and making required associations as well. It makes all of these creation and association in behind seen. That is an incredible power of Spring. @Autowired is used for injecting one instance of SessionFactory, if you’re worry about performance issue, you can define your SessionFactory bean as a singleton scope. For complete information about autowiring, read Spring autowiring example.

    @Autowired将帮助您注入所需的实例。 那就是依赖注入或IoC(控制反转)概念。 这是一个重要的概念,它意味着不允许开发人员控制创建实例和进行所需关联的过程。 它使所有这些创建和关联都在后面看到。 这是Spring不可思议的力量。 @Autowired用于注入SessionFactory的一个实例,如果您担心性能问题,可以将SessionFactory bean定义为单例作用域。 有关自动装配的完整信息,请阅读Spring autowiring example
  • @Transactional annotation is used for Transaction Demarcation purpose. Transaction demarcation is used for associating your contextual session with an active Transaction. That will cause a CRUD operation to get executed against your own database. You should go through Spring Declarative Transaction Management Example.

    @Transactional批注用于事务划分目的。 事务划分用于将上下文会话与活动事务相关联。 这将导致针对您自己的数据库执行CRUD操作。 您应该阅读Spring声明式事务管理示例

Primefaces托管Bean – RegisterEmployee (Primefaces Managed Bean – RegisterEmployee)

Managed Bean is a JSF facility, and it’s used for handling all required User Interface validations. In a layered application, Managed Bean is used for invoking Business services. You may be wondering once you know that it’s applicable for you to inject EmployeeService Spring bean into your own Managed Bean. That becomes true if you’re used @ManagedProperty annotation.

Managed Bean是一种JSF工具,用于处理所有必需的用户界面验证。 在分层应用程序中,托管Bean用于调用业务服务。 一旦知道将EmployeeService Spring bean注入到您自己的Managed Bean中,您可能会想知道。 如果使用@ManagedProperty批注,那将变为事实。

faces-config.xml

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="https://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
	version="2.2">
<application>
	<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
package com.journaldev.prime.faces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import com.journaldev.hibernate.data.Employee;
import com.journaldev.spring.service.EmployeeService;

@ManagedBean
@SessionScoped
public class RegisterEmployee {

	@ManagedProperty("#{employeeService}")
	private EmployeeService employeeService;

	private Employee employee = new Employee();

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String register() {
		// Calling Business Service
		employeeService.register(employee);
		// Add message
		FacesContext.getCurrentInstance().addMessage(null, 
				new FacesMessage("The Employee "+this.employee.getEmployeeName()+" Is Registered Successfully"));
		return "";
	}
}

Here’s detailed explanation for the above code:

以下是上述代码的详细说明:

  • RegisterEmployee Managed Bean is developed with using of @ManagedProperty annotation that will help you get a Spring EmployeeService instance injected. That association won’t be applicable if you don’t provide a special faces-config.xml file that contains a newly added Spring’s el-resolver.

    RegisterEmployee托管Bean是使用@ManagedProperty批注开发的,它将帮助您获得Spring EmployeeService实例的注入。 如果您不提供包含新添加的Spring的el-resolver的特殊faces-config.xml文件,则该关联将不适用。
  • Primefaces UI form will help you gather all required information about registered employee.

    Primefaces UI表单将帮助您收集有关注册员工的所有必需信息。
  • Register action will ask EmployeeService saving given employee instance.

    注册操作将要求EmployeeService保存给定的雇员实例。

Primefaces –注册表 (Primefaces – Register Form)

index.xhtml

index.xhtml

<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:ui="https://java.sun.com/jsf/facelets"
	xmlns:h="https://java.sun.com/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core"
	xmlns:p="https://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
	<title>Register Employee</title>
</h:head>
<h:form>
	<p:growl id="messages"></p:growl>
	<p:panelGrid columns="2">
		<p:outputLabel value="Enter Employee Name:"></p:outputLabel>
		<p:inputText value="#{registerEmployee.employee.employeeName}"></p:inputText>
		<p:outputLabel value="Enter Employee Hire Date:"></p:outputLabel>
		<p:calendar value="#{registerEmployee.employee.employeeHireDate}"></p:calendar>
		<p:outputLabel value="Enter Employee Salary:"></p:outputLabel>
		<p:inputText value="#{registerEmployee.employee.employeeSalary}"></p:inputText>						
	</p:panelGrid>
	<p:commandButton value="Register" action="#{registerEmployee.register}" update="messages"></p:commandButton>
</h:form>
</html>

Spring PrimefacesHibernate示例摘要 (Spring Primefaces Hibernate Example Summary)

Hibernate integration with Spring and Primefaces is a popular development task. This tutorial guides you thoroughly to get Hibernate integrated with Spring and Primefaces that would lead you into getting an employee persisted against your database. Some technical details are mentioned intentionally. Contribute us by commenting below and find the source code for downloading purpose.

与Spring和Primefaces的Hibernate集成是一项流行的开发任务。 本教程彻底指导您将Hibernate与Spring和Primefaces集成在一起,这将使您使员工坚持使用数据库。 有意提及一些技术细节。 通过在下面评论来为我们贡献力量,并找到用于下载目的的源代码。

翻译自: https://www.journaldev.com/4096/primefaces-spring-hibernate-integration-example-tutorial

primefaces教程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PrimeFaces主要标签学习。 1 PrimeFaces综述 3 1.1 安装 3 1.2 配置,JSF2.0环境下用PrimeFace2.x 4 1.3 Hello World入门示例 4 1.4 UI组件: 4 2 UI组件 5 2.1 布局 5 2.1.1 Layout 页面布局 5 2.1.2 Panel用于包含其它组件,提供象windows窗口式的外观。 8 2.1.3 TabView 分页式面板组件 8 2.1.4 OutputPanel 仅用于显示元素 9 2.1.5 Fieldset 9 2.1.6 Dashboard 仪表盘 10 2.1.7 Themeswitcher 主题切换器,动态切换主题 11 2.1.8 Separator空白分隔区域 11 2.1.9 Spacer行内加空格 11 2.2 菜单 11 2.2.1 Menu 11 2.2.2 Menubar 12 2.2.3 MenuButton 13 2.2.4 Toolbar 13 2.2.5 Stack :堆叠式菜单(竖向) 13 2.2.6 Dock :动画鱼眼式菜单(横向) 14 2.3 按钮: 15 2.3.1 Button 15 2.3.2 CommandButton 15 2.3.3 CommandLink 17 2.3.4 ContextMenu 17 2.3.5 HotKey 17 2.4 输入组件 18 2.4.1 文本输入 18 2.4.1.1 Editor 18 2.4.1.2 Password 19 2.4.1.3 Password Strength 19 2.4.1.4 inputMask 输入掩码,实现格式化输入。 19 2.4.1.5 InputText 20 2.4.1.6 InputTextarea 20 2.4.1.7 Watermark :文本输入内容提示 20 2.4.1.8 Keyboard 显示一个虚拟键盘,用以支持输入字符。 21 2.4.1.9 Inplace 替换文本 22 2.4.2 选择式输入 22 2.4.2.1 AutoComplete :自动补全 22 2.4.2.2 PickList 选择列表 25 2.4.2.3 Slider 滑动条 26 2.4.2.4 Spinner 27 2.4.3 其它格式数据的输入: 27 2.4.3.1 Spreadsheet电子表格 27 2.4.3.2 Calendar 各种格式的日期输入与显示 28 2.4.3.3 Schedule 日程计划输入组件 31 2.4.3.4 Captcha :变形字符验证 31 2.4.3.5 Color Picker 32 2.5 集合(复杂格式)数据的输出与显示: 33 2.5.1 BreadCrumb :层次化页面导航条 >…>….> 33 2.5.2 Accordion:一个容器组件,它用tab动态地显示折叠或展开过程。 34 2.5.3 Carousel:多用途,标签式、分布式显示 35 2.5.4 Galleria 图片陈列廊 36 2.5.5 LightBox :图片加亮显示 37 2.5.6 DataGrid 数据栅格 37 2.5.7 DataList 用列表的形式显示数据,每个栅格可显示多个数据项 39 2.5.8 DataTable数据表格 41 2.5.9 Tree 树形显示 46 2.5.10 TreeTable 树表 47 2.5.11 DragDrop 50 2.5.11.1 Draggable组件: 50 2.5.11.2 Droppable组件 51 2.5.12 Charts基于flash的图形生成与显示 52 2.6 数据导出: 54 2.6.1 Data Exporter 54 2.6.2 Printer 56 2.7 状态: 56 2.7.1 ProgressBar 56 2.7.2 NotificationBar 57 2.8 对话框: 58 2.8.1 ConfirmDialog 58 2.8.2 Dialog 58 2.9 图形图像多媒体: 59 2.9.1 ImageCompare :提供丰富的接口比较两副图像 59 2.9.2 Graphic Text 文本图象化显示 60 2.9.3 ImageCropper 60 2.9.4 ImageSwitch 61 2.9.5 Google Maps 地图 61 2.9.6 Dyna Image 63 2.9.7 Media 65 2.9.8 Star Rating 65 2.9.9 Wizard: 66 2.10 消息: 66 2.10.1 Growl Mac风格的消息显示 66 2.10.2 Message/Messages 67 2.10.3 Tooltip 67 2.11 文件处理: 67 2.11.1 FileUpload 上传文件 67 2.11.2 FileDownload 下载文件 69 2.11.3 IdleMonitor 屏幕凝滞 70 2.11.4 Terminal 70 2.12 辅助功能(辅助其它JSF组件,给它们添加新的功能和行为): 71 2.12.1 Ajax Engine 71 2.12.2 Ajax Poll轮询 72 2.12.3 Ajax远程调用p:remoteCommand 72 2.12.4 Ajax Status 显示ajax后台运行状态。 72 2.12.5 Focus 73 2.12.6 Effect: 73 2.12.7 Collector : 74 2.12.8 Resizable 给任何JSF组件添加可调整大小的行为。 74 2.12.9 RequestContext : 75 3 TouchFaces 76 3.1.1 移动UI工具 76 3.1.2 Ajax Push/Comet 77 3.1.3 几分钟实现聊天应用: 78 4 附录 79 4.1 全部UI组件列表 84 4.2 PrimeFaces常用属性集 85

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值