Primefaces, Spring 4 with JPA (Hibernate 4/EclipseLink) Example Tutorial

Filed Under: PrimeFaces

Java Persistence API is a standard specification. It provides a persistence model that’s implemented by different implementer frameworks.

Primefaces Spring Hibernate EclipseLink

Hibernate & EclipseLink are two most popular implementations used for persisting given business model against some sort of persistence store like relational database. As such, this tutorial will provide you a full-fledged example containing all required configuration steps to developer a layered application that uses:

  1. Primefaces components to develop a compelling User Interface that aimed to handle user’s interactions and verify user’s inputs.
  2. Hibernate/EclipseLink implementations to develop an Object/Relational Mapping beneath JPA umbrella.
  3. Spring framework as a kind of glue that get everything attached each together.

We’ve discussed before using Hibernate ORM for persisting given domain classes. But today we will use only JPA based configurations.

JPA specification does its bootstrap in a different way. In hibernate we’ve bootstrapped our application using hibernate.cfg.xml file, but JPA doesn’t specify that file.

JPA provides another way of configuration, it’s using persistence.xml file that is located within your classpath and under META-INF folder.

Let’s see how can we use both of Hibernate and EclipseLink for implementing a single registration form.

Primefaces Spring JPA Hibernate EclipseLink Example Required Tools

Before proceeding far away, you must prepare your environments that should contain for:

  • JDK 1.6+.
  • Eclipse Kepler 4.3.
  • Hibernate 4.3.6.Final.
  • Spring 4.0.3.RELEASE.
  • EclipseLink 2.5.0-RC1
  • Maven Build Tool
  • MySQL 5.x.

Primefaces Spring JPA Hibernate EclipseLink Example Project Structure

Primefaces Spring JPA Hibernate EclipseLink Example

Primefaces Spring JPA Hibernate EclipseLink Example Database Tables

We have Employee table in our MySQL database, you can use below script to create it.

Database Tables - Create Employee Table


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;
  • Employee Table contains one Primary Key with Auto Increment value.

Primefaces Spring JPA Hibernate EclipseLink Example Domain Classes

We have also one domain class that would be persisting into our database Employee table.

Employee.java


package com.journaldev.hibernate.jpa.data;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Employee {
	@Id
	@Column(name="EMP_ID")
	private long employeeId;
	@Column(name="EMP_NAME")
	private String employeeName;
	@Column(name="EMP_HIRE_DATE")
	@Temporal(TemporalType.TIMESTAMP)
	private Date employeeHireDate;
	@Column(name="EMP_SALARY")
	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;
	}
}
  • JPA provides @Entity which will be used for indicating Employee as a persistent domain class. Default mapping would be happening in order to map this persistent entity with its Employee Table. In case you’ve provided Table name or class name that aren’t identical, @Table must be used.
  • @Id annotation used for indicating identity of a given Employee instance. Because of discrepancies between attribute name and column name, @column must be provided.
  • @Column name annotation takes a parameter of mapped column name.

Primefaces Spring JPA Hibernate EclipseLink Example Persistence Unit

As we’ve mentioned earlier, JPA provides an alternative way for bootstrapping JPA framework, it’s a persistence.xml file. The minimum amount of this file should look like:

persistence.xml


<persistence 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"
	version="2.0">
	<!-- Will be referenced in Spring Context File -->
	<persistence-unit name="jpa-persistence" transaction-type="RESOURCE_LOCAL">
		<class>com.journaldev.hibernate.jpa.data.Employee</class>
		<properties>
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/journaldev" />
			<property name="javax.persistence.jdbc.user" value="pankaj" />
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.password" value="pankaj123" />
		</properties>
	</persistence-unit>
</persistence>

Persistence unit should define:

  • Persistence unit name. That name will be referenced by Spring context.
  • Transaction type – JPA implementation have the choice of managing the resource by itself (RESOURCE_LOCAL) or having them managed by the application server’s JTA implementation.
  • Information about database connection.

Primefaces Spring JPA Hibernate EclipseLink Example Maven Dependencies

All required libraries are listed within pom.xml file that’s read by Maven itself.

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.journaldev</groupId>
	<artifactId>Primefaces-Hibernate-JPA-Spring-Integration-Sample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Primefaces-Hibernate-JPA-Spring-Integration-Sample Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>http://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- 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>
		<!-- Hibernate 4.3.6 core library library -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.6.Final</version>
		</dependency>
		<!-- Hibernate 4.3.6 JPA support -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.6.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>
		<!-- Dependencies for Eclipse JPA Persistence API -->
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>eclipselink</artifactId>
			<version>2.5.0-RC1</version>
		</dependency>
	</dependencies>
	<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>
</project>

Hibernate/JPA Spring Configuration

Persisting using of JPA requires an instance of EntityManager. This instance can be acquired by configuring a proper Spring context.

applicationContext.xml


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

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://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>

	<!-- Necessary to get the entity manager injected into the factory bean -->
	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />	

	<!-- Define Hibernate JPA Vendor Adapter -->
	<bean id="jpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="databasePlatform"
			value="org.hibernate.dialect.MySQLDialect" />
	</bean>	

	<!-- Entity Manager Factory -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="hibernate.jpa"></property>
		<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
	</bean>

	<!-- Transaction Manager -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<!-- Detect @Transactional -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
  1. JPA require an entityManagerFactory object which is an instance of org.springframework.orm.jpa.LocalEntityFactoryBean. This instance must be provided with the name of persistenceUnit and a JPAVendorAdapter.
  2. To use @Trasnactional annotation properly, TransactionManager should be defined.
  3. Default name and location for Spring context configuration is applicationContext.xml and beneath of WEB-INF folder.

EclipseLink/JPA Spring Configuration

Same configuration would be used for EclipseLink, a small change is required is to provide EclipseLink’s JPA vendor. Just change the jpaVendorAdapter bean to below and the JPA implementation used will be EclipseLink.

applicationContext.xml


	<!-- Define EclipseLink JPA Vendor Adapter -->
	<bean id="jpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
		<property name="databasePlatform"
			value="org.eclipse.persistence.platform.database.MySQLPlatform" />
		<property name="generateDdl" value="false" />
		<property name="showSql" value="true" />
	</bean>

Primefaces Deployment Descriptor

Proper configuration of Spring requires adding of Spring listener into Primefaces’ deployment descriptor web.xml application.

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" 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>

Spring EmployeeService

Spring service is the interaction point between presentation layer and persistence layer. If you’re familiar with DAO, you can consider it something similar.

EmployeeService.java


package com.journaldev.spring.service;

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

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.hibernate.jpa.data.Employee;

@Component
public class EmployeeService {
	@PersistenceContext
	private EntityManager em;

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@Transactional
	public void register(Employee emp) {
		// Save employee
		this.em.persist(emp);
	}
}
  1. EntityManager is injected using @PersistenceContext annotation. Even you’ve defined an instance of EntityManagerFactory, but a JPA implementation will be very smart to inject you an instance of EntityManager. EntityManager would be something similar for Session in Hibernate. In case you’ve invoked any of its CRUD operation within both of context and active transaction, your operation would be persisted against your persistence store. Note that em.persist() and using of @Transactional annotation upon register method.

Primefaces Managed Bean – RegisterEmployee

RegisterEmployee is a faces managed bean that’s used for handling user interaction and validation of user’s input.

ResgiterEmployee.java


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.jpa.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 "";
	}
}
  • Spring service EmployeeService is injected using Spring el-reslover that get declared with your faces-config.xml.
  • Register method would delegate the invocation into an injected EmployeeService instance. As such, EmployeeService would handle real registration.

Primefaces Employee Registration Page

index.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://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>

Primefaces Spring JPA EclipseLink Employee Registered

Primefaces Spring JPA EclipseLink Employee Persisted

Primefaces Spring JPA Hibernate EclipseLink Example Summary

This tutorial aimed to help you get both of Hibernate and EclipseLink JPA implementations used into your project. JPA has changed your life, it’s so easy to configure, use and track. It’s plugged in with a default logging mechanism that would help you find your problem shortly. Contribute us by commenting below and find downloaded source code.

Comments

  1. HF says:

    Nice tutorial. Too bad it does not work. @ManagedProperties are not set. Both the EntityManager and the employeeService stay uninstanciated.

    1. HF says:

      Rechecked my project.. I overread the passage mentioning the faces-config.xml. After adding the file to the project the injection worked as expected.

  2. Luiz Vercosa says:

    Hello, thanks a lot. It worked. I only needed to create database myself in mysql.

  3. ed says:

    it is bad configuration. This sample is not to use. You can lost your time reading this.

  4. nalaka says:

    Hi,
    I just want to know what if faces controller bean set to view scope.all examples i have found uses session scope.

    Thank you.

  5. pape says:

    this all printer console for my error to insert into database I need help …

    java.lang.NullPointerException
    javax.el.ELException: java.lang.NullPointerException
    at org.apache.el.parser.AstValue.invoke(AstValue.java:258)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:818)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:146)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:279)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.NullPointerException
    at com.pape.dieng.service.EmployeeService.register(EmployeeService.java:23)
    at com.pape.dieng.faces.bean.RegisterEmployee.register(RegisterEmployee.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    … 32 more

  6. pape says:

    i Have this probleme when try to insert into database :
    Caused by: java.lang.NullPointerException
    at com.pape.dieng.faces.bean.RegisterEmployee.register(RegisterEmployee.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    … 32 more

  7. Humeynat says:

    how will it be DAO this example

    1. Mohammad says:

      Hi Humeynat,

      DAO is a design pattern and you always a choice to make it or not. Ideally, we have defined a DAO class to make sure we have a fully separated classes that are responsible to communicate with the database.

      Spring has eliminated the need for defining that, as Spring is defining a separate layer that talk with the persistence layer without and interferer.

      Regards

  8. Forrest Faber says:

    Hi,

    I have used your tutorial as a model for my own application. I am able to create entities as well as list them. The problem I’m having is that the update does not work. Only the last field in the form is getting updated. I’m probably doing something stupid. Below is some relevant code. No matter what I try, only the second field in editAccount.xhtml will update. Thanks for any help in advance!

    //View

    Admin

    //Entity
    @Entity
    public class Account {

    @Id
    @GeneratedValue
    @Column(name=”id”)
    private Long id;

    @Column(name=”account_number”, length=32)
    private String accountNumber;

    @Column(name=”description”, length=256)
    private String description;

    public Long getId() {
    return id;
    }

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

    public String getAccountNumber() {
    return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
    this.accountNumber = accountNumber;
    }

    public String getDescription() {
    return description;
    }

    public void setDescription(String description) {
    this.description = description;
    }

    }

    //Bean
    @ManagedBean
    @SessionScoped
    public class AccountBean {

    @ManagedProperty(“#{accountService}”)
    AccountService accountService;

    private Long accountId;

    public Long getAccountId() {
    return accountId;
    }
    public void setAccountId(Long accountId) {
    this.accountId = accountId;
    }

    private Account account;
    private List accounts;

    public AccountService getAccountService() {
    return accountService;
    }

    public void setAccountService(AccountService accountService) {
    this.accountService = accountService;
    }

    public Account getAccount() {
    if(accountId != null)
    setAccount(accountService.getAccount(accountId));
    else
    setAccount(accountService.getAccount(2L));

    return account;
    }

    public void setAccount(Account account) {
    this.account = account;
    }

    public List getAccounts() {
    this.accounts = accountService.getAccounts();
    return this.accounts;
    }

    public void setAccounts(List accounts) {
    this.accounts = accounts;
    }

    public String update() {
    accountService.update(account);
    return “”;
    }
    public String create() {
    accountService.create(account);
    return “”;
    }

    }

    //Service Bean

    @Component
    public class AccountService {

    @PersistenceContext
    private EntityManager em;

    public EntityManager getEm() {
    return em;
    }
    public void setEm(EntityManager em) {
    this.em = em;
    }
    @Transactional
    public Account getAccount(Long id) {
    return this.em.find(Account.class, id);
    }

    @Transactional
    public List getAccounts() {

    return em.createQuery(“from Account account”).getResultList();

    }

    @Transactional
    public void create(Account account) {
    this.em.persist(account);
    }

    @Transactional
    public void update(Account account){
    this.em.merge(account);
    }

    }

    1. Mohammad says:

      Hi Forrest Faber,

      Please double check that you have a proper binding inside your page, it works fine according for your note, so you may need to double check somethings you may not take care of. Try to make it simple action that’s doing what you are trying to do through the page.

      Regards,

  9. Martin says:

    when you say: Persistence unit name. That name will be referenced by Spring context.
    (persistence-unit name=”jpa-persistence” transaction-type=”RESOURCE_LOCAL”>)

    you should do :

    <property name="persistenceUnitName" value="jpa-persistence“>

    ( value=”jpa-persistence” instead of value=”hibernate.jpa” )

    I think, because I had an error.

    1. Mohammad says:

      Hi Martin,

      Let me know the error that you had.

      Regards,

  10. omar says:

    Hi It worked for me
    You have to edit two things one comes from faces-config.xml and the other applicationContext.xml
    It´s in the source code the difference.
    Thanks a lot!

  11. Majid MOstafavi says:

    INFO: OpenWebBeans Container has started, it took 89 ms.
    Dec 12, 2014 5:53:48 PM org.apache.openejb.assembler.classic.Assembler createApplication
    INFO: Deployed Application(path=/home/majid/Project/spring-jpa-primefaces-tutorial-master/target/primefaces-spring-jpa-tutorial)
    2014-12-12 17:53:50,761 INFO [org.springframework.web.context.ContextLoader] –
    2014-12-12 17:53:51,015 INFO [org.springframework.web.context.support.XmlWebApplicationContext] –
    2014-12-12 17:53:51,141 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] –
    2014-12-12 17:53:51,674 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] –
    2014-12-12 17:53:52,259 INFO [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] –
    2014-12-12 17:53:52,283 INFO [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] –
    2014-12-12 17:53:52,479 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource] –
    2014-12-12 17:53:52,676 INFO [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] –
    2014-12-12 17:53:52,727 INFO [org.hibernate.jpa.internal.util.LogHelper] –
    2014-12-12 17:53:52,908 INFO [org.hibernate.Version] –
    2014-12-12 17:53:52,912 INFO [org.hibernate.cfg.Environment] –
    2014-12-12 17:53:52,914 INFO [org.hibernate.cfg.Environment] –
    2014-12-12 17:53:53,162 ERROR [org.springframework.web.context.ContextLoader] –
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in file [/home/majid/Project/spring-jpa-primefaces-tutorial-master/target/primefaces-spring-jpa-tutorial/WEB-INF/classes/META-INF/spring/applicationContext-db.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/Convert
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.tomee.catalina.TomcatWebAppBuilder.deployWar(TomcatWebAppBuilder.java:622)
    at org.apache.tomee.catalina.TomcatWebAppBuilder.deployWebApps(TomcatWebAppBuilder.java:593)
    at org.apache.tomee.catalina.deployment.TomcatWebappDeployer.deploy(TomcatWebappDeployer.java:44)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:168)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:182)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:164)
    at org.apache.openejb.security.internal.InternalSecurityInterceptor.invoke(InternalSecurityInterceptor.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:182)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:164)
    at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:180)
    at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:99)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:182)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:164)
    at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:80)
    at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:212)
    at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:181)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.doEjbObject_BUSINESS_METHOD(EjbRequestHandler.java:370)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.processRequest(EjbRequestHandler.java:181)
    at org.apache.openejb.server.ejbd.EjbDaemon.processEjbRequest(EjbDaemon.java:344)
    at org.apache.openejb.server.ejbd.EjbDaemon.service(EjbDaemon.java:240)
    at org.apache.openejb.server.ejbd.EjbServer.service(EjbServer.java:86)
    at org.apache.openejb.server.httpd.ServerServlet.service(ServerServlet.java:58)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:45)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    Caused by: java.lang.NoClassDefFoundError: javax/persistence/Convert
    at org.hibernate.metamodel.source.annotations.JPADotNames.(JPADotNames.java:134)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.prepareMetadataSources(EntityManagerFactoryBuilderImpl.java:386)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.(EntityManagerFactoryBuilderImpl.java:224)
    at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:51)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:182)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:177)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    … 70 more
    Caused by: java.lang.ClassNotFoundException: javax.persistence.Convert
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
    at org.apache.tomee.catalina.LazyStopWebappClassLoader.loadClass(LazyStopWebappClassLoader.java:109)
    … 81 more

    1. Mohammad Amr says:

      Hi Majid,

      You may need to add those missing JARs, so can you please take a look into your Maven file.

      javax.persistence.Convert class not into your classpath.

      Regards,

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages