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集成示例。 框架之间的集成是一项复杂的任务,并且通常需要很多时间才能实现。 我们已经在单独的教程中讨论了Primefaces , Spring和Hibernate框架,但是这次我们将向您展示如何集成所有框架以创建分层(分层)应用程序。
Layered (tiered) application is a popular design that most of the enterprise applications are aligned with. In which:
分层(分层)应用程序是一种流行的设计,大多数企业应用程序都与之保持一致。 其中:
This tutorial intended for implementing a layered application using all of these listed frameworks.
本教程旨在使用所有列出的框架来实现分层的应用程序。
Before getting started delve into, let’s see the required tools that you would need for:
在开始深入研究之前,让我们看一下所需的必需工具:
Our final project structure will look like below image, we will go through each of the components one by one.
我们的最终项目结构将如下图所示,我们将逐一介绍每个组件。
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;
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;
}
}
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>
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配置过程需要执行以下步骤:
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>
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:
以下是上述代码的详细说明:
StandardServiceRegistryBuilder
to build SessionFactory. 使用最新版本的hibernate要求您使用StandardServiceRegistryBuilder
来构建SessionFactory。 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:
这是上面给出的代码的详细说明:
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中获得有关此配置的更多详细信息。
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:
以下是上述代码的详细说明:
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:
以下是上述代码的详细说明:
@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文件,则该关联将不适用。 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>
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教程