RSS

JPA basic example with EntityManager , Spring and Maven

06 Jul

Visit my new website http://java4developers.com

In this post we are going to make a project that allows us to get from a mySql database a car list. The technologies we are going to use are Maven for the dependency management, JPA to interact with the database, Spring to define the our application context (besides of wiring everything), and finally we use JUnit to our application tests.


Our pom.xml will be like this..

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hopcroft.examples.spring</groupId>
	<artifactId>simpledao</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<pluginRepositories>
		<pluginRepository>
			<id>maven-annotation</id>
			<url>http://maven-annotation-plugin.googlecode.com/svn/trunk/mavenrepo</url>
		</pluginRepository>

	</pluginRepositories>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<compilerArguments>
						<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
					</compilerArguments>
				</configuration>
				<version>2.3.2</version>
			</plugin>
			<plugin>
				<groupId>org.bsc.maven</groupId>
				<artifactId>maven-processor-plugin</artifactId>
				<version>2.0.2</version>
				<executions>
					<execution>
						<id>process</id>
						<goals>
							<goal>process</goal>
						</goals>
						<phase>generate-sources</phase>
						<configuration>
							<outputDirectory>src/main/generated-java</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<version>1.6</version>
				<executions>
					<execution>
						<id>add-source</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>add-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>src/main/generated-java</source>
							</sources>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>ejb3-persistence</artifactId>
			<version>1.0.2.GA</version>
			<type>pom</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.0.5.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.0.0.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.0.5.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>javax.security</groupId>
			<artifactId>jacc</artifactId>
			<version>1.0</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.10</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.0.5.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.1</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.12.1.GA</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.5.0-Final</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.5.0-Final</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.codehaus.openxma</groupId>
			<artifactId>dsl-platform</artifactId>
			<version>3.6.3</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-jpamodelgen</artifactId>
			<version>1.0.0.Final</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
	</dependencies>
</project>

Our application will have the next structure.
configuracionProyecto en hop2croft.wordpress.com

We have a domain model layer where there is a Car entity that mirrors the database table.

Base de datos mySql hop2croft.wordpress.com

Our car entity:

package com.hopcroft.examples.domain;

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

@Entity
@Table(name = "Car")
public class Car {
	@Id
	@Column(name = "id")
	private long id;
	@Column(name = "company")
	private String company;
	@Column(name = "model")
	private String model;
	@Column(name = "price")
	private long price;

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

	public long getId() {
		return id;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public long getPrice() {
		return price;
	}

	public void setPrice(long price) {
		this.price = price;
	}

}

We have also a data access layer where there is a interface called CarDao that defines the methods that we use to interact with our database. This interface will be implemented by the CarDaoImpl.
In some of the later projects we have use a HibernateTemplate object to get the data from our database. Instead of that we are going to use an EntityManager instance. An EntityManager will be a instance of an EntityManagerFactory within JPA. This type of factory means the configuration used to access to our database.
To use JPA in our project we are going to create a persistence unit in the META-INF/persistence.xml file. Within this file we will have a specified persistence unit. What we should do is choosing the transaction type. We need to use the provider that will implement JPA. In our case, we are going to use Hibernate.

<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_1_0.xsd"
	version="1.0">
	<persistence-unit name="JpaPersistenceUnit"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
	</persistence-unit>
</persistence>

We need to configure our application context in the same way we did when we used an Hibernate sessionFactory. That means, we have to add a dataSource within our context file where we define our url , user, password and the database we are going to use. We define an entityManagerFactory to which we pass the newly created dataSource. This entityManagerFactory object will be controlled by a transactionManager. As we are using JPA we need a org.springframework.orm.jpa.JpaTransactionManager.
There is also a component-scan element. We will explain it when we see our Dao. Our context file is as follows:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost/test"
		p:username="root" p:password="" p:initialSize="5" p:maxActive="10">
	</bean>

	<bean
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		id="entityManagerFactory">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<context:component-scan base-package="com.hopcroft.examples.dao">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Repository" />
	</context:component-scan>

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

	<tx:annotation-driven mode="aspectj"
		transaction-manager="transactionManager" />

	<context:spring-configured />
	<context:annotation-config />
</beans>

After take a look to our configuration files we need to explain our Dao (interface and its implementation).

package com.hopcroft.examples.dao;

import java.util.List;

import org.springframework.dao.DataAccessException;

import com.hopcroft.examples.domain.Car;

public interface CarDao {
	public List<Car> getCars() throws DataAccessException;
	public Car getCar(Long carId) throws DataAccessException;
}

package com.hopcroft.examples.dao;

import java.util.List;

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

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hopcroft.examples.domain.Car;

@Repository
public class CarDaoImpl implements CarDao {

	protected EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Transactional
	public List<Car> getCars() throws DataAccessException {
		Query query = getEntityManager().createQuery("select c from Car c");
		List<Car> resultList = query.getResultList();
		return resultList;
	}
	@Transactional
	public Car getCar(Long carId) throws DataAccessException {
		return getEntityManager().find(Car.class, carId);
	}
}

There is no much to say about the carDao interface. Two methods that we implement within the CarDaoImpl class. We need to explain a couple of things.

First of all we notice that CarDaoImpl is annotated as @Repository. This is an annotation we use to say to the Spring context that our CarDaoImpl is included within its context as a component. Besides the @Repository annotation there are a @Service annotation and a @Controller one. Every annotation extends to the @Component annotation. There is a meaning difference among them, @Repository will indicate our Spring context that we want to add a Dao bean, @Controller a controller and @Service … easy to guess. Do you remenber thecomponent-scan element within our testApplicationContext file?, in this file we tell Spring we are going to incluide as beans every single class with the @Repository annotation, in our case, CarDaoImpl car.

The second annotation we notice is @PersistenceContext. It is in the EntityManager setter method. We get an EntiyManagerFactory object we need for address our database.

We can notice that our methods are annontated as transactional. That means our methods belong to a unique transaction that will be management by the transactionManager we explained in our context file.

Our method logic is quite straightforward. We have a couple of methods, the first one list every car we have stored in our database and the second one use an id to find a specified car. To that we have to use an entityManager. As with HibernateTemplate, our entityManager class will have some basic methods like persist, refresh ó remove. Once our application is created we are going to make a test class.

package com.hopcroft.examples.test;

import java.util.List;
import java.util.logging.Logger;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.hopcroft.examples.dao.CarDao;
import com.hopcroft.examples.domain.Car;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/testApplicationContext.xml" })
public class CarTest {

	@Autowired
	private CarDao carDao;
	private Logger logger = Logger.getLogger("myLog");
	private Long id;

	@Before
	public void init() {
//		carNumber = carDao.getCars().size();
		id = 1L;
	}

	@Test
	public void listCarsTest() {
		List<Car> cars = carDao.getCars();
//		logger.info("Cars: " + cars.size());
		Assert.assertNotNull(cars);
		Assert.assertEquals(15, cars.size());
	}

	@Test
	public void getCarTest() {
		Car car = carDao.getCar(id);
		Assert.assertEquals(id.longValue(), car.getId());
		Assert.assertEquals("Boxster", car.getModel());
	}
}

We annotate our class as always, pointing that we are going to use JUnit4 and the context file we have already created. We are going to get our CarDao from the Spring context. We have some method that we are going to test from a Maven test configuration within STS.

test maven en hop2croft.wordpress.com

Everything is correct now in our log.

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building simpleDaoEntityManager 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ simpleDaoEntityManager ---
[WARNING] Using platform encoding (MacRoman actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ simpleDaoEntityManager ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ simpleDaoEntityManager ---
[WARNING] Using platform encoding (MacRoman actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ simpleDaoEntityManager ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.5:test (default-test) @ simpleDaoEntityManager ---
[INFO] Surefire report directory: /Users/Ivan/Documents/workspace/hsqldb/simpleDaoEntityManager/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.hopcroft.examples.test.CarTest
04-jul-2011 21:06:44 org.springframework.test.context.TestContextManager retrieveTestExecutionListeners
INFO: @TestExecutionListeners is not present for class [class com.hopcroft.examples.test.CarTest]: using defaults.
04-jul-2011 21:06:45 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [testApplicationContext.xml]
04-jul-2011 21:06:46 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@c4a5ec: startup date [Mon Jul 04 21:06:46 CEST 2011]; root of context hierarchy
04-jul-2011 21:06:47 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@a93995: defining beans [dataSource,entityManagerFactory,carDaoImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,transactionManager,org.springframework.transaction.config.internalTransactionAspect,org.springframework.context.config.internalBeanConfigurerAspect]; root of factory hierarchy
04-jul-2011 21:06:47 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'JpaPersistenceUnit'
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/Ivan/.m2/repository/org/ow2/easybeans/easybeans-uberjar-hibernate/1.2.1/easybeans-uberjar-hibernate-1.2.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/Ivan/.m2/repository/org/slf4j/slf4j-jcl/1.5.2/slf4j-jcl-1.5.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
04-jul-2011 21:06:47 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate Annotations 3.5.0-Final
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate 3.5.0-Final
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: hibernate.properties not found
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Bytecode provider name : javassist
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: using JDK 1.4 java.sql.Timestamp handling
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate Commons Annotations 3.2.0.Final
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate EntityManager 3.5.6-Final
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Processing PersistenceUnitInfo [
	name: JpaPersistenceUnit
	...]
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Binding entity from annotated class: com.hopcroft.examples.domain.Car
04-jul-2011 21:06:48 org.slf4j.impl.JCLLoggerAdapter info
INFO: Bind entity com.hopcroft.examples.domain.Car on table Car
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate Validator not found: ignoring
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate Validator 1.2.1
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
04-jul-2011 21:06:49 org.slf4j.impl.JCLLoggerAdapter info
INFO: Using provided datasource
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: RDBMS: MySQL, version: 5.5.11
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.10 ( Revision: ${svn.Revision} )
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Automatic flush during beforeCompletion(): disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Automatic session close at end of transaction: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: JDBC batch size: 15
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: JDBC batch updates for versioned data: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Scrollable result sets: enabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: JDBC3 getGeneratedKeys(): enabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Connection release mode: auto
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Maximum outer join fetch depth: 2
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Default batch fetch size: 1
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Generate SQL with comments: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Order SQL updates by primary key: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Order SQL inserts for batching: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Using ASTQueryTranslatorFactory
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Query language substitutions: {}
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: JPA-QL strict compliance: enabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Second-level cache: enabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Query cache: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Optimize cache for minimal puts: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Structured second-level cache entries: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Statistics: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Deleted entity synthetic identifier rollback: disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Default entity-mode: pojo
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Named query checking : enabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): disabled
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Hibernate Search 3.2.0.CR1
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: building session factory
04-jul-2011 21:06:50 org.slf4j.impl.JCLLoggerAdapter info
INFO: Not binding factory to JNDI, no JNDI name configured
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.813 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

04-jul-2011 21:06:51 org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@c4a5ec: startup date [Mon Jul 04 21:06:46 CEST 2011]; root of context hierarchy
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.313s
[INFO] Finished at: Mon Jul 04 21:06:51 CEST 2011
[INFO] Final Memory: 6M/12M
[INFO] ------------------------------------------------------------------------

Some post you find interesting somewhat:

 
17 comentarios

Publicado por en 6 julio, 2011 en J2EE, JPA

 

Etiquetas: , , , , , ,

17 Respuestas a “JPA basic example with EntityManager , Spring and Maven

  1. zoostar

    27 octubre, 2012 at 2:51 pm

    The above example is very good except I feel the transactional context has to be applied at the service layer. Other than that, it’s a very good and complete example. Thanks.

     
    • hop2croft

      29 octubre, 2012 at 2:29 pm

      Hi Zoostar,

      thank you for reading the post. Yes, you are right it would be a clearer example if I would have created some transactional services to access to the data layer.

      Regards-

       
  2. peoplemerge (@peoplemerge)

    13 diciembre, 2012 at 1:30 am

    Also, it would be great to have downloadable samples

     
    • hop2croft

      15 diciembre, 2012 at 4:32 pm

      thanks for reading. I’ll try to find this post’s code and upload it to my Github account

       
  3. bunkertor

    23 febrero, 2013 at 7:17 pm

    Reblogged this on Agile Mobile Developer.

     
  4. Juan Rivillas

    15 julio, 2013 at 5:58 pm

    A nice example, but it’s no working for me. Will be fine if you upload the complete code

     
    • hop2croft

      15 agosto, 2013 at 8:59 pm

      Hi Juan,

      thank you for reading my blog. Unfortunately I already deleted those projects 😦

       
  5. Pedrola

    6 agosto, 2013 at 9:40 pm

    thank you very much, this article was really useful for me

     
  6. Aleksandra Jakoska

    15 noviembre, 2013 at 3:05 pm

    Can you please remake this project, is very simple shouldn’t take much time

     
    • hop2croft

      23 diciembre, 2013 at 12:01 pm

      Hi Aleksandra,

      thank you for reading the post and apologies for answering this late. Recreate the project is very easy. One thing you can do is simply creating the skeleton of a maven app following a maven archetype. There are different types of archetype for everything. In this case I followed the webapp archetype. If you have maven installed in your laptop, you just need to run:

      mvn archetype:generate -DgroupId=com.hopcroft.examples.spring -DartifactId=simpledao -DarchetypeArtifactId=maven-archetype-webapp -Dversion=0.0.1-SNAPSHOT -DinteractiveMode=false

      After that copy the different files in the post within the project just created. And that’s all … :). Hope it helps.

      Bye!!

       
  7. Ari (@aritz86)

    7 febrero, 2014 at 2:46 pm

    Good tuto, congrats. Tested and working for me, it obtains the full car list and finds a car by id. Problem comes for me when I want a Car to be saved: javax.persistence.TransactionRequiredException: no transaction is in progress. It happens to me everytime I call flush() on the EntityManager. Have a look at my test project in GitHub, there’s a test case with the issue: https://github.com/xtremebiker/jsf-spring-test

     
    • Ari (@aritz86)

      7 febrero, 2014 at 3:00 pm

      Forget about that, I just got it working removing ‘mode=»aspectj»‘ from my ‘tx:annotation-driven’ declararion.

       
  8. Niranjan Velakanti

    4 octubre, 2014 at 7:19 pm

    its been ver useful to me.

     

Replica a Juan Rivillas Cancelar la respuesta