Getting Started With JPA in Spring 2.0 |
|

The motivation behind this blog entry is to provide a simple step-by-step guide for getting started with JPA in a standalone environment with the Spring Framework. While the JPA specification originated as the persistence mechanism for EJB 3.0, it was fortunately recognized that any such mechanism should in fact be able to persist simple POJOs. Therefore, with a handful of JARs in your classpath and a few Spring-configured beans, you can begin experimenting with JPA code within your favorite IDE. I will be using Glassfish JPA – which is the reference implementation and is based upon Oracle’s TopLink ORM framework.
Initial Setup
Ensure that you are using Java 5 (a prerequisite for JPA as well as EJB 3.0).
Download the glassfish JPA jar from: https://glassfish.dev.java.net/downloads/persistence/JavaPersistence.html
(NOTE: I used the “V2_build_02″ jar, but any later version should also work.)
To unbundle the jar from the “installer� jar, run:
java -jar glassfish-persistence-installer-v2-b02.jar
(this is required for acceptance of the license agreement)
Add the toplink-essentials.jar to your classpath
Add the JAR containing your database driver (I am using hsqldb.jar version 1.8.0.1 in the example, but only minor changes are necessary to adapt for another database).
Add the following Spring JARs using the 2.0 M5 versions (available here: http://sourceforge.net/project/showfiles.php?group_id=73357).
- spring.jar
- spring-jpa.jar
- spring-mock.jar
Finally, add these jars to your classpath as well:
- commons-logging.jar
- log4j.jar
- junit.jar
Code – Domain Model
This example will be based on a purposefully simple domain model of just 3 classes. Notice the use of annotations. With JPA, one may choose to use either annotations or an XML file to specify the object-relational mapping metadata – or even a combination of both approaches. Here, I have chosen to use solely annotations – for which brief descriptions will be provided immediately following the domain model code listings.
First, the Restaurant class:
package blog.jpa.domain;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
@Entity
public class Restaurant {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
private Address address;
@ManyToMany
@JoinTable(inverseJoinColumns = @JoinColumn(name = "ENTREE_ID"))
private Set<Entree> entrees;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Set<Entree> getEntrees() {
return entrees;
}
public void setEntrees(Set<Entree> entrees) {
this.entrees = entrees;
}
}
Second, the Address class:
package blog.jpa.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "STREET_NUMBER")
private int streetNumber;
@Column(name = "STREET_NAME")
private String streetName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
}
Third, the Entree class:
package blog.jpa.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Entree {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private boolean vegetarian;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isVegetarian() {
return vegetarian;
}
public void setVegetarian(boolean vegetarian) {
this.vegetarian = vegetarian;
}
}
As you can see, not every persistent field has been annotated. JPA uses defaults (such as using a column name that matches the property name exactly) so that in many cases you do not need to specify the metadata explicitly. However, you may still choose to do so in order to provide more thoroughly self-documenting code. Notice that in the Entree class I am not using annotations for the String property “name� or the boolean property “vegetarian�. However, in the Address class, I am using the annotations, because I want to have a non-default name for the columns in the database (for example, I have chosen “STREET_NAME� whereas the default would have been “STREETNAME�).
Of course, one of the most important features of any ORM mechanism is the way in which one specifies the mapping from relationships between Objects to their database counterparts. In the Restaurant class, there is a @OneToOne annotation to describe the relationship to an Address and a @ManyToMany annotation to describe the relationship with members of the Entree class. Since instances of these other classes are also being managed by the EntityManager, it is possible to specify “cascade� rules. For example, when a Restaurant is deleted, the associated Address will also be deleted. In a moment, you will see a testcase for this scenario.
Finally, take a look at the @Id annotations and the specified “strategy� for the ID’s @GeneratedValue. This metadata is used for describing the primary key generation strategy which in turn controls the identity within the database.
To learn much more about these and additional JPA annotations, check out the JPA specification – which is actually a subset of JSR-220.
Code – Data Access Layer
For accessing instances of the domain model, it is best to create a generic interface that hides all details about the underlying persistence mechanism. That way, if switching later to something other than JPA, there will be no impact on the architecture. This also makes it easier to test the service layer, since it enables the creation of stub implementations of this data access interface – or even dynamic mock implementations.
Here is the interface. Notice that there are no dependencies on any JPA or Spring classes. In fact, the only dependencies here that are not core Java classes are the classes of my domain model (in this simple case, there is only one – Restaurant):
package blog.jpa.dao;
import java.util.List;
import blog.jpa.domain.Restaurant;
public interface RestaurantDao {
public Restaurant findById(long id);
public List<Restaurant> findByName(String name);
public List<Restaurant> findByStreetName(String streetName);
public List<Restaurant> findByEntreeNameLike(String entreeName);
public List<Restaurant> findRestaurantsWithVegetarianEntrees();
public void save(Restaurant restaurant);
public Restaurant update(Restaurant restaurant);
public void delete(Restaurant restaurant);
}
For the implementation of this interface, I am going to extend Spring’s JpaDaoSupport class. This provides a convenience method for retrieving the JpaTemplate. If you have used Spring with JDBC or other ORM technologies, then you will probably be quite familiar with this approach.
It should be noted that use of the JpaDaoSupport is optional. It is possible to construct a JpaTemplate directly by simply providing the EntityManagerFactory to its constructor. In fact, the JpaTemplate itself is optional. If you do not wish to have the automatic translation of JPA exceptions into Spring’s runtime exception hierarchy, then you can avoid JpaTemplate altogether. In that case, you may still be interested in Spring’s EntityManagerFactoryUtils class which provides a convenient static method for obtaining the shared (and thus transactional) EntityManager.
Here is the implementation:
package blog.jpa.dao;
import java.util.List;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import blog.jpa.domain.Restaurant;
public class JpaRestaurantDao extends JpaDaoSupport implements RestaurantDao {
public Restaurant findById(long id) {
return getJpaTemplate().find(Restaurant.class, id);
}
public List<Restaurant> findByName(String name) {
return getJpaTemplate().find("select r from Restaurant r where r.name = ?1", name);
}
public List<Restaurant> findByStreetName(String streetName) {
return getJpaTemplate().find("select r from Restaurant r where r.address.streetName = ?1", streetName);
}
public List<Restaurant> findByEntreeNameLike(String entreeName) {
return getJpaTemplate().find("select r from Restaurant r where r.entrees.name like ?1", entreeName);
}
public List<Restaurant> findRestaurantsWithVegetarianEntrees() {
return getJpaTemplate().find("select r from Restaurant r where r.entrees.vegetarian = 'true'");
}
public void save(Restaurant restaurant) {
getJpaTemplate().persist(restaurant);
}
public Restaurant update(Restaurant restaurant) {
return getJpaTemplate().merge(restaurant);
}
public void delete(Restaurant restaurant) {
getJpaTemplate().remove(restaurant);
}
}
The Service Layer
As the purpose here is to focus on a JPA implementation for the data-access layer, the service layer is omitted. Obviously, in a realistic scenario, the service layer would play a critical role in the system architecture. It would be the point where transactions are demarcated – and typically, they would be demarcated declaratively in the Spring configuration. In the next step, when you have a look at the configuration, you will notice that I have provided a “transactionManagerâ€? bean. It is used by the base test class to automatically wrap each test method in a transaction, and it is the same “transactionManagerâ€? that would wrap service layer methods with transactions. The main point to take away is that there is NO transaction-related code in the data-access tier. Using the Spring JpaTemplate ensures that the same EntityManager is shared across all DAOs. Therefore transaction propagation occurs automatically – as dictated by the service layer. In other words, it will actually behave exactly the same as other persistence mechanisms configured within the Spring framework. There is nothing JPA-specific – hence the rationale for leaving it out of this entry which is focused on JPA.
Configuration
Since I opted for the annotation-based mappings, you have actually already seen most of the JPA-specific configuration when the domain classes were presented. As mentioned above, it also would have been possible to configure those mappings via XML (in an ‘orm.xml’ file). The only other required configuration is in ‘META-INF/persistence.xml’. In this case, that is very simple since the database-related properties will be available to the EntityManagerFactory via a dependency-injected “dataSource� provided in the Spring configuration (due up next). The only other information in this ‘persistence.xml’ is whether to use local or global (JTA) transactions. Here are the contents of the ‘persistence.xml’ file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"> <persistence-unit name="SpringJpaGettingStarted" transaction-type="RESOURCE_LOCAL"/> </persistence>
There are only 4 beans in the Spring configuration (well ok, a couple of inner-beans too). First, there is the “restaurantDaoâ€? (I purposefully left “jpaâ€? out of the bean name since any service layer beans depending on the DAO should only be concerned with the generic interface). The only required property for the JPA implementation of this DAO is the “entityManagerFactoryâ€? which it uses to create the JpaTemplate. The “entityManagerFactoryâ€? depends on the “dataSourceâ€?, and there is nothing JPA-specific about that. In this configuration, you will see a DriverManagerDataSource, but in production code, this would be replaced by a connection pool – and typically one obtained via a JndiObjectFactoryBean (or Spring 2.0’s new convenience
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<bean id="restaurantDao" class="blog.jpa.dao.JpaRestaurantDao">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.ContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="oracle.toplink.essentials.platform.database.HSQLPlatform"/>
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost/"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
First you see that the “entityManagerFactory� needs to be aware of a “dataSource�. Next there is the “jpaVendorAdapter� as there are a variety of JPA implementations. In this case, I’ve configured the TopLinkJpaVendorAdapter as an inner bean, and it has a few properties of its own. There is a boolean property to specify whether SQL should be shown and another boolean property for the generation of DDL. Both of these have been set to “true� and thus the database schema will be automatically generated each time the tests are executed. This is rather convenient in the early development phase as it provides immediate feedback for experimentations in the mappings, column names, etc. The “databasePlatformClass� provides the necessary information of what particular database is being used. Finally, the “entityManagerFactory� has a property for a “loadTimeWeaver� that plays a role in the transformation of class files by JPA persistence providers in order to accomodate certain features such as lazy-loading.
Integration Testing
Perhaps the best way to learn a new API is to write a bunch of testcases. The JpaRestaurantDaoTests class provides some basic tests. In order to learn more about JPA, modify the code and/or configuration and observe the impact on these tests. For example, try modifying the cascade settings – or the cardinality of the associations. Notice that JpaRestaurantDaoTests extends Spring’s AbstractJpaTests. You may already be familiar with Spring’s AbstractTransactionalDataSourceSpringContextTests. This class will behave the same way in that any database changes caused by the test methods will rollback by default. AbstractJpaTests actually does much more than that, but it is beyond the scope of this entry to go into those details. If interested, have a look at the source code for AbstractJpaTests.
Here is the JpaRestaurantDaoTests code:
package blog.jpa.dao;
import java.util.List;
import org.springframework.test.jpa.AbstractJpaTests;
import blog.jpa.dao.RestaurantDao;
import blog.jpa.domain.Restaurant;
public class JpaRestaurantDaoTests extends AbstractJpaTests {
private RestaurantDao restaurantDao;
public void setRestaurantDao(RestaurantDao restaurantDao) {
this.restaurantDao = restaurantDao;
}
protected String[] getConfigLocations() {
return new String[] {"classpath:/blog/jpa/dao/applicationContext.xml"};
}
protected void onSetUpInTransaction() throws Exception {
jdbcTemplate.execute("insert into address (id, street_number, street_name) values (1, 10, 'Main Street')");
jdbcTemplate.execute("insert into address (id, street_number, street_name) values (2, 20, 'Main Street')");
jdbcTemplate.execute("insert into address (id, street_number, street_name) values (3, 123, 'Dover Street')");
jdbcTemplate.execute("insert into restaurant (id, name, address_id) values (1, 'Burger Barn', 1)");
jdbcTemplate.execute("insert into restaurant (id, name, address_id) values (2, 'Veggie Village', 2)");
jdbcTemplate.execute("insert into restaurant (id, name, address_id) values (3, 'Dover Diner', 3)");
jdbcTemplate.execute("insert into entree (id, name, vegetarian) values (1, 'Hamburger', 0)");
jdbcTemplate.execute("insert into entree (id, name, vegetarian) values (2, 'Cheeseburger', 0)");
jdbcTemplate.execute("insert into entree (id, name, vegetarian) values (3, 'Tofu Stir Fry', 1)");
jdbcTemplate.execute("insert into entree (id, name, vegetarian) values (4, 'Vegetable Soup', 1)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (1, 1)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (1, 2)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (2, 3)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (2, 4)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (3, 1)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (3, 2)");
jdbcTemplate.execute("insert into restaurant_entree (restaurant_id, entree_id) values (3, 4)");
}
public void testFindByIdWhereRestaurantExists() {
Restaurant restaurant = restaurantDao.findById(1);
assertNotNull(restaurant);
assertEquals("Burger Barn", restaurant.getName());
}
public void testFindByIdWhereRestaurantDoesNotExist() {
Restaurant restaurant = restaurantDao.findById(99);
assertNull(restaurant);
}
public void testFindByNameWhereRestaurantExists() {
List<Restaurant> restaurants = restaurantDao.findByName("Veggie Village");
assertEquals(1, restaurants.size());
Restaurant restaurant = restaurants.get(0);
assertEquals("Veggie Village", restaurant.getName());
assertEquals("Main Street", restaurant.getAddress().getStreetName());
assertEquals(2, restaurant.getEntrees().size());
}
public void testFindByNameWhereRestaurantDoesNotExist() {
List<Restaurant> restaurants = restaurantDao.findByName("No Such Restaurant");
assertEquals(0, restaurants.size());
}
public void testFindByStreetName() {
List<Restaurant> restaurants = restaurantDao.findByStreetName("Main Street");
assertEquals(2, restaurants.size());
Restaurant r1 = restaurantDao.findByName("Burger Barn").get(0);
Restaurant r2 = restaurantDao.findByName("Veggie Village").get(0);
assertTrue(restaurants.contains(r1));
assertTrue(restaurants.contains(r2));
}
public void testFindByEntreeNameLike() {
List<Restaurant> restaurants = restaurantDao.findByEntreeNameLike("%burger");
assertEquals(2, restaurants.size());
}
public void testFindRestaurantsWithVegetarianOptions() {
List<Restaurant> restaurants = restaurantDao.findRestaurantsWithVegetarianEntrees();
assertEquals(2, restaurants.size());
}
public void testModifyRestaurant() {
String oldName = "Burger Barn";
String newName = "Hamburger Hut";
Restaurant restaurant = restaurantDao.findByName(oldName).get(0);
restaurant.setName(newName);
restaurantDao.update(restaurant);
List<Restaurant> results = restaurantDao.findByName(oldName);
assertEquals(0, results.size());
results = restaurantDao.findByName(newName);
assertEquals(1, results.size());
}
public void testDeleteRestaurantAlsoDeletesAddress() {
String restaurantName = "Dover Diner";
int preRestaurantCount = jdbcTemplate.queryForInt("select count(*) from restaurant");
int preAddressCount = jdbcTemplate.queryForInt("select count(*) from address where street_name = 'Dover Street'");
Restaurant restaurant = restaurantDao.findByName(restaurantName).get(0);
restaurantDao.delete(restaurant);
List<Restaurant> results = restaurantDao.findByName(restaurantName);
assertEquals(0, results.size());
int postRestaurantCount = jdbcTemplate.queryForInt("select count(*) from restaurant");
assertEquals(preRestaurantCount - 1, postRestaurantCount);
int postAddressCount = jdbcTemplate.queryForInt("select count(*) from address where street_name = 'Dover Street'");
assertEquals(preAddressCount - 1, postAddressCount);
}
public void testDeleteRestaurantDoesNotDeleteEntrees() {
String restaurantName = "Dover Diner";
int preRestaurantCount = jdbcTemplate.queryForInt("select count(*) from restaurant");
int preEntreeCount = jdbcTemplate.queryForInt("select count(*) from entree");
Restaurant restaurant = restaurantDao.findByName(restaurantName).get(0);
restaurantDao.delete(restaurant);
List<Restaurant> results = restaurantDao.findByName(restaurantName);
assertEquals(0, results.size());
int postRestaurantCount = jdbcTemplate.queryForInt("select count(*) from restaurant");
assertEquals(preRestaurantCount - 1, postRestaurantCount);
int postEntreeCount = jdbcTemplate.queryForInt("select count(*) from entree");
assertEquals(preEntreeCount, postEntreeCount);
}
}
Further Reading
JPA is a vast topic, and this blog has only scratched the surface – the main objective being to demonstrate the basic configuration of a JPA-based persistence implementation with Spring. Obviously this domain model is trivial in terms of Object-Relational mapping. However, once you have this working configuration, you will be able to extend the example here while exploring the ORM capabilities offered by JPA. I would highly encourage a closer look at the Spring JPA support via the JavaDoc and the Spring reference documentation. The 2.0 RC1 release contains an added sub-section on JPA within the ORM section of the reference document.
Here are a few helpful links:
JSR-220 (contains the JPA specification)
Glassfish JPA (the reference implementation)
Kodo 4.0 (BEA’s JPA implementation based on Kodo)
Hibernate JPA Migration Guide
Similar Posts
- Spring 2.0's JMS Improvements
- What's New in Spring Integration 2.2.RC1 (Part 1 – MongoDb)
- Annotation-Driven Dependency Injection in Spring 2.1
- Dynamic DataSource Routing
- Customizing Annotation Configuration and Component Detection in Spring 2.1





ehsavoie says:
Added on August 3rd, 2006 at 7:46 amHi,
in RC2 with a slight correction
The example is working fine
should be
.
I'm trying to add transaction annotation to your DAO. When I add :
All goes wrong
((
Error creating bean with name 'restaurantDao' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor': Cannot create inner bean '(inner bean)' while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restaurantDao' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor': Cannot create inner bean '(inner bean)' while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor': Cannot create inner bean '(inner bean)' while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor': Cannot create inner bean '(inner bean)' while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:239)
What am I missing ??
Thanks
Emmanuel
ehsavoie says:
Added on August 3rd, 2006 at 7:49 amSorry the XML was removed
(
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.ContainerEntityManagerFactoryBean">
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<tx:annotation-driven transaction-manager="transactionManager"/>
ehsavoie says:
Added on August 3rd, 2006 at 8:13 amThis seems to be a bug with RC2 (http://forum.springframework.org/showthread.php?t=26771&highlight=tx:annotation-driven).
Ali says:
Added on August 11th, 2006 at 11:50 amHi,
Thx for your Tutorial but unfortunately doesn’t work!
can you please getting your example working
and this ContainerEntityManagerFactoryBean does'nt exit so i replace it with LocalContainerEntityManagerFactoryBean
I've got the Same Problem
Thx
Best Regards
Ali
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restaurantDao' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Error setting property values; nested exception is PropertyAccessExceptionsException (1 errors)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Error setting property values; nested exception is PropertyAccessExceptionsException (1 errors)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [blog/jpa/dao/applicationContext.xml]: Error setting property values; nested exception is PropertyAccessExceptionsException (1 errors)
Caused by: PropertyAccessExceptionsException (1 errors)
org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [org.hsqldb.jdbcDriver]; nested exception is java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [org.hsqldb.jdbcDriver]; nested exception is java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
Caused by: java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
at org.springframework.instrument.classloading.ShadowingClassLoader.doLoadClass(ShadowingClassLoader.java:97)
at org.springframework.instrument.classloading.ShadowingClassLoader.loadClass(ShadowingClassLoader.java:58)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:160)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:138)
at org.springframework.jdbc.datasource.DriverManagerDataSource.setDriverClassName(DriverManagerDataSource.java:148)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:737)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:575)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValue(AbstractPropertyAccessor.java:49)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:68)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:57)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:816)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:392)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:240)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:132)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:237)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:153)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:225)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:114)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:801)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:392)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:240)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:132)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:237)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:153)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:225)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:114)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:801)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:392)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:240)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:132)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:237)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:153)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:254)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:337)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.springframework.test.jpa.AbstractJpaTests.runBare(AbstractJpaTests.java:212)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Ali says:
Added on August 14th, 2006 at 6:13 amThe Example works Fun after some correction!
Thx
Ali
Andre says:
Added on August 22nd, 2006 at 6:47 pmHi,
I am running into this problem :
Exception Description: A problem was encountered resolving the class name – The descriptor for [Restaurant] was not found.
You guys that got this example goign which mods did you have to do ?
regards,
Andre
Andre says:
Added on August 22nd, 2006 at 6:58 pmOk!!
Got it working know from in Eclipse.
This worked for me :
I added an instance of org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean for my entityManagerFactory. The important thing was to set the persistenceXmlLocation property. This refers to ones persistnce.xml file which should in the classpath.
My Config :
persistence.xml
Andrew S says:
Added on October 12th, 2006 at 2:29 amHi , i looking for example how run spring 2.0 with toplink jpa on j2se application. Can anybody help ??
Paul Smith says:
Added on October 16th, 2006 at 2:09 amGreat blog. The example worked perfectly for me.
However, it would be great if you could follow up with the details on how to run the same example using a Java SE main() method (instead of the test program, where the test extends AbstractJpaTests). I have tried to make it work, but unfortunately, I end up with the following error:
Object is not a known entity type.
Here is my main() (same as your example, but with my own data):
public static void main(String[] args) {
ApplicationContext appCtxt = new ClassPathXmlApplicationContext("conf/spring.xml");
meetService = (MeetDao)appCtxt.getBean("meetDao");
Meet meet = new Meet();
MeetTest.setWithTestValues(meet, "test1");
meetService.save(meet);
}
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3178)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:170)
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.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:237)
at $Proxy11.persist(Unknown Source)
at org.springframework.orm.jpa.JpaTemplate$5.doInJpa(JpaTemplate.java:255)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:183)
at org.springframework.orm.jpa.JpaTemplate.persist(JpaTemplate.java:253)
at dao.MeetDaoJpa.save(MeetDaoJpa.java:31)
at dao.MeetDaoTest3.main(MeetDaoTest3.java:20)
I'm a spring novice, so I'm probably forgetting something obvious.
Any insight into this would be *greatly* appreciated.
Thanks,
Paul
sateesh says:
Added on October 18th, 2006 at 12:00 pmHi,
Has any one tried running this sample in NetBeans??
Do i need to have AspectJ Module installed inorder to run this one !!
Thanks
Sateesh
sateesh says:
Added on October 18th, 2006 at 2:35 pm[quote comment="638"]Hi,
Has any one tried running this sample in NetBeans??
Do i need to have AspectJ Module installed inorder to run this one !!
I tried running this Example in NetBeans and getting a ClassNotFoundException .Here is the complete stack trace..
log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.ContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [META-INF/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.ContainerEntityManagerFactoryBean
Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.ContainerEntityManagerFactoryBean
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:177)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:313)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:912)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:165)
at org.springframework.context.support.AbstractApplicationContext.getBeanNamesForType(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:397)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:330)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:92)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:77)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:68)
at blog.jpa.dao.TestDao.main(TestDao.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I have included all the required jar Files in the classpath and i am using Spring 2.0 version..
Thanks
Sateesh[/quote]
sateesh says:
Added on October 18th, 2006 at 3:04 pmHi All,
I added the following Bean to the applicationContext.xml
and i have another Class with main() whose code is listed below..
public static void main(String[] args) {
ApplicationContext appCtxt = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
JpaRestaurantDaoTests testsDao = (JpaRestaurantDaoTests)appCtxt.getBean("testsDao");
try{
testsDao.onSetUpInTransaction();
testsDao.testDeleteRestaurantAlsoDeletesAddress();
testsDao.testDeleteRestaurantDoesNotDeleteEntrees();
testsDao.testFindByEntreeNameLike();
testsDao.testFindByIdWhereRestaurantDoesNotExist();
testsDao.testFindByIdWhereRestaurantExists();
testsDao.testFindByNameWhereRestaurantDoesNotExist();
testsDao.testFindByNameWhereRestaurantExists();
testsDao.testFindByStreetName();
testsDao.testFindRestaurantsWithVegetarianOptions();
testsDao.testModifyRestaurant();
}
catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
It looks like i need to create the tables before running this as i am getting the below Excep..
[TopLink Config]: 2006.10.18 03:56:46.938–ServerSession(19533676)–Thread(Thread[main,5,main])–The source foreign key column name for the many to many mapping [private java.util.Set blog.jpa.domain.Restaurant.entrees] is being defaulted to: Restaurant_ID.
[TopLink Config]: 2006.10.18 03:56:46.938–ServerSession(19533676)–Thread(Thread[main,5,main])–The target primary key column name for the many to many mapping [private java.util.Set blog.jpa.domain.Restaurant.entrees] is being defaulted to: ID.
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [insert into address (id, street_number, street_name) values (1, 10, 'Main Street')]; nested exception is java.sql.SQLException: ORA-00942: table or view does not exist
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [insert into address (id, street_number, street_name) values (1, 10, 'Main Street')]; nested exception is java.sql.SQLException: ORA-00942: table or view does not exist
Caused by: java.sql.SQLException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:330)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:287)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:742)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:206)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:945)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1159)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1678)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1644)
at org.springframework.jdbc.core.JdbcTemplate$1ExecuteStatementCallback.doInStatement(JdbcTemplate.java:336)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:310)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:343)
at blog.jpa.dao.JpaRestaurantDaoTests.onSetUpInTransaction(JpaRestaurantDaoTests.java:40)
at blog.jpa.dao.TestDao.main(TestDao.java:29)
BUILD SUCCESSFUL (total time: 2 seconds)
Sateesh
Jim Shingler says:
Added on October 24th, 2006 at 10:00 amMark, This blog was VERY helpful.
I would like to set this up with Hibernate instead of Toplink. This has been a challenge. It is a lot easier to do with Toplink than Hibernate. Could you do a follow-up that shows how to do the same thing with Hibernate.
Thanks
Jim
lou says:
Added on January 10th, 2007 at 12:02 pmthanks for the samples …
im running into two more or less big problems which one of you guys might have already served.
Im trying to setup my application using the underlying hibernate o/m.
Adding the ContainerEntityManagerFactoryBean results directly in a:
Error creating bean with name 'entityManagerFactory' defined in class path resource [jpa-datasource.xml]: Invocation of init method failed; nested exception is java.lang.LinkageError: Class org/xml/sax/Parser violates loader constraints
Caused by: java.lang.LinkageError: Class org/xml/sax/Parser violates loader constraints
which im not yet able to solve.
Using the LocalEntityManagerFactoryBean requires a complete hibernate configuration in the persistence.xml :
Although this configuration works, (hibernates connects properly ) my Entities ( created them the way it was described here –> annotations )
do not get mapped to the db.
im using maven 2, spring 2.0.1 and hibernate 3.2.1.ga …
any help is appreciated …
Nikolay says:
Added on February 1st, 2007 at 6:01 amHello. Can you please consult me where I can download interface21 jar? My email is nikolay.forums@gmail.com.
Thank you in advance!
Michiel says:
Added on February 14th, 2007 at 5:16 pmHi,
Nice example to get me started. Thanks.
I managed to get it working with Hibernate, although not all JUnit test passed out of the box. First of all there is a problem with using 'true' in HQL queries, it results in a SMALLINT/CHAR conflict on my Derby database. After removing the quotes, the problem is over (switching back to Toplink still works as well). The second problem was that the tests for findByEntreeNameLike() and findByEntreeNameLike() returned too many rows, 4 instead of 2. This was fixed by using "select distinct".
Hmm… so much for JPA provider independence.
thomas says:
Added on February 21st, 2007 at 1:21 pm[quote post="32"]Great blog. The example worked perfectly for me.
However, it would be great if you could follow up with the details on how to run the same example using a Java SE main() method (instead of the test program, where the test extends AbstractJpaTests). [/quote]
Unfortunately i stepped in the same issue. I got it not work as a standalone Java SE application. I implemented the main-method like usal.
Is there anybody outthere whos achieved to get it work out from main() (still in spring)?
Or, what i have to take care about?
thomas
thomas says:
Added on February 21st, 2007 at 2:41 pmnow, i found a solution:
http://forum.springframework.org/showthread.php?t=30193#2
you had to use the org … classloading.InstrumentationLoadTimeWeaver instead of the SimpleLoadTimeWeaver in combination with the VM argument: -javaagent:/spring-agent.jar
but i dont know why i had to do this …
jb says:
Added on March 6th, 2007 at 6:02 amI have problem to test de App. When I ran these tests I says: No persistence units parsed from {classpath*:META-INF/persistence.xml}. When I put a persistence.xml in my META-INF it says:
Error creating bean with name 'usuarioDao' defined in file [C:\Documents and Settings\Administrador\workspace2\Padron\build\classes\com\telvent\padron\domain\dao\test\test-applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\Documents and Settings\Administrador\workspace2\Padron\build\classes\com\telvent\padron\domain\dao\test\test-applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.RuntimeException: error trying to scan : file:/C:/Documents and Settings/Administrador/workspace2/Padron/build/classes/
And I've never put a in my persistence.xml
regards, josé
arsenalist says:
Added on March 6th, 2007 at 3:10 pmI have it working fine but with a different configuration:
and that's it. mydb is defined in the persistence.xml file:
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
com.arsenalist.User
This is working fine for me. Any shortcomings of this method?
Samuel Le Berrigaud says:
Added on March 28th, 2007 at 6:14 amHi,
I started to look at JPA and thought I would start with this tutorial. I am not using the Glassfish implementation though and opted for OpenJPA.
I am having trouble with the load time weaver it seems. When trying to persist an object the framework cannot cast it to 'PersistenceCapable'.
I tried different configuration:
- using the SimpleLoadTimeWeaver without the spring agent,
- using the InstrumentationLoadTimeWeaver with the spring agent,
with Spring 2.0.3 and openjpa 0.9.6 as well as 0.9.7-SNAPSHOT… This is all done outside in unit tests (outside any container).
When using the OpenJPA PCEnhancer after the compilation phase (and before running the tests) it does work!
I am lost, any idea?
Thanks.
Rene Richard says:
Added on June 15th, 2007 at 12:23 pmHere's a good example which talks about spring/jpa/hibernate
http://cwiki.apache.org/S2WIKI/struts-2-spring-2-jpa-ajax.html
Rene Richard says:
Added on June 15th, 2007 at 12:24 pmre example … also need hibernate-commons-annotations.jar also in the classpath
Roman Sykora says:
Added on July 26th, 2007 at 7:10 amHi, first I'd like to say that I really liked your article. It helped me a lot to set things up quickly and get a running example.
Doing the tests I had problems with:
blog.jpa.dao.JpaRestaurantDao#findByStreetName(String streetName)
blog.jpa.dao.JpaRestaurantDao#findByEntryNameLike(String entreeName)
I used Glassfish persistence (toplink-essentials v2-b50g) which seemed the latest milestone release as to date.
I'll not post the full stacktrace since it's a little bit messy and hard to read. The important line is:
Exception Description: Error compiling the query [select r from Restaurant r where r.entrees.name like ?1], line 1, column 36: invalid navigation expression [r.entrees.name], cannot navigate collection valued association field [entrees].
changing the related queries fixed that problem for me.
"select distinct r from Restaurant r join r.entrees e where e.name like ?1"
"select distinct r from Restaurant r join r.entrees e where e.vegetarian = 'true'"
regards
Roman Sykora
vamsee lakamsani says:
Added on November 12th, 2007 at 3:06 amHi, Thanks for the sample. I got it it work after reading the blog as well as some user comments. I tried changing it a bit so I can add/persist new restaurants using the JpaTemplate. The original sample seems to be using direct jdbc to create stuff in onSetUpInTransaction. Not sure why. why not use JpaTemplate to create everything? I ran into a problem when I tried creating a restaurant. I described the details by replying to another user in the spring forum who was seeing a similar problem in his app. I saw the problem in my app too but decided to reproduce it in this sample.
http://forum.springframework.org/showthread.php?p=150400#post150400
TIA for any suggestions.
vamsee lakamsani says:
Added on November 13th, 2007 at 2:41 amProblem looks like load time weaver related. The entity not found error went away when I switched to this load time weaver.
http://static.springframework.org/spring/docs/2.0.x/reference/orm.html#orm-jpa-loadtimeweaver
carol mcdonald says:
Added on January 7th, 2008 at 10:47 amHave you tried JPA and Spring 2.x on Glassfish V2 ?
I get the following error:
javax.el.ELException: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: Exception Description: Cannot use an EntityTransaction while using JTA.
With Glassfish V1, I could use Spring 2.0 & JPA with a container managed entity manager :
@PersistenceContext(unitName = "PetCatalogPu")
private EntityManager em;
To do this, I had to configure The Entity Manager factory and the transactionManager in the spring applicationContext.xml :
..
…
this no longer works in Glassfish v2 , apparently because the Spring JpaTransactionManager does not use JTA .
I noticed that spring provides a JTA manager for Weblogic and Websphere:
Khosro says:
Added on February 2nd, 2008 at 11:26 amhello Mark and hello to all,
I have serious problems,i googling but could not found
anything useful.
I divide my errors in two parts.
errors that i got with Hibernate and errors that i got with
TopLink.
1.In Hibernate
1.1.In hibernate if i set the "transaction-type" in
persistence.xml to JTA i got the following error:
""org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory' defined
in ServletContext resource [/WEB-INF/applicationContext.xml]:
Invocation of init method failed; nested exception is
javax.persistence.PersistenceException:
org.hibernate.HibernateException: The chosen transaction
strategy requires access to the JTA TransactionManager""
When i change the "transaction-type" to RESOURCE_LOCAL it
works,and when i click bottun to add to DB the page refresh
but the intance does not add to DB.WHY?(I do not get any
error).
1.2.My entity class is Article.when i run my project in
hibernate with transaction-type="RESOURCE_LOCAL",the page
display but when i click to add the Article instance to DB i
got the following error:
""""com.sun.rave.web.ui.appbase.ApplicationException: #
{insert.add_action}:
org.springframework.dao.InvalidDataAccessApiUsageException:
Unknown entity: iranjava.model.Article; nested exception is
java.lang.IllegalArgumentException: Unknown entity:
iranjava.model.Article""""
I found i must explicitly add Article entity to
persistence.xml.
i mean, i must:
iranjava
false
Conclusion in Hibernate:
So far i set the transaction-type="RESOURCE_LOCAL" and
explicitly add the Article instance to DB the project run,but
when i click button to add to DB it does not added to
DB,meanwhile i do not get any error.
2.In TopLink:
2.1.with transaction-type="JTA" ,the project run but when i
want to add instance to DB i got the following error:
""java.lang.IllegalArgumentException: Object:
iranjava.model.Article[id=6] is not a known entity type.""
and i must declare :
iranjava
if i do not,i got error.
I beg you help me?
Thank.
Khosro.
MG says:
Added on March 14th, 2008 at 4:08 pmI am getting a similar error with QuerySyntaxException, entity is not mapped. My entityManager looks like:
classpath:/META-INF/persistence.xml
I haven't been able to find a definitive answer for why the test won't run. The application runs fine. Some signs point to persistence.xml, but if I delete the file and try to re-run the test I get a configuration error because of the missing persistence unit. Any help/comments would be appreciated.
Erhan Elgün says:
Added on March 26th, 2008 at 10:14 amthanks for the nice article. After reading your blog article, many thing is clear in my mind about spring jpa configuration.
But i wonder how a "delete from …." or "insert into " statement can be executed with "getJpaTemplate(). …" ??
alessandro says:
Added on April 15th, 2008 at 4:52 amYour guide is interesting.
I like especially the Integration Testing part.
Bye.
Note:
I would like to point out that the link
Hibernate JPA Migration Guide
is not working and that the new address is as follows:
Java Persistence Migration Guide
http://www.hibernate.org/398.html
Dinesh says:
Added on July 15th, 2008 at 6:41 amHi,
I followed your code and implemented as a sample where Employee is an object in place of Restuarant. Everything is working fine except the delete. I am getting the following exception in delete operation. Please help me how to resolve this issue.
Thanks & Regards,
Dinesh
org.springframework.dao.InvalidDataAccessApiUsageException: Entity must be managed to call remove: p
oc.employee.domain.Employee@e376b4, try merging the detached and try the remove again.; nested excep
tion is java.lang.IllegalArgumentException: Entity must be managed to call remove: poc.employee.doma
in.Employee@e376b4, try merging the detached and try the remove again.
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible
(EntityManagerFactoryUtils.java:229)
at org.springframework.orm.jpa.DefaultJpaDialect.translateExceptionIfPossible(DefaultJpaDial
ect.java:113)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java
:212)
at org.springframework.orm.jpa.JpaAccessor.translateIfNecessary(JpaAccessor.java:152)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:196)
at org.springframework.orm.jpa.JpaTemplate.remove(JpaTemplate.java:278)
at poc.employee.jpa.EmployeeDaoImpl.deleteEmployee(EmployeeDaoImpl.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310
)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMe
thodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvo
cation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInte
rceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvo
cation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy83.deleteEmployee(Unknown Source)
at poc.employee.service.EmpDetailsManagerImpl.deleteEmployee(EmpDetailsManagerImpl.java:60)
at poc.employee.controller.EmployeeController.deleteEmp(EmployeeController.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.springframework.web.servlet.mvc.multiaction.MultiActionController.invokeNamedMethod(M
ultiActionController.java:473)
at org.springframework.web.servlet.mvc.multiaction.MultiActionController.handleRequestIntern
al(MultiActionController.java:410)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.j
ava:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControlle
rHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:808)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:523
)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:463)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.
java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletC
ontext.java:3395)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2
140)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2046)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
Caused by: java.lang.IllegalArgumentException: Entity must be managed to call remove: poc.employee.d
omain.Employee@e376b4, try merging the detached and try the remove again.
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.performRemove(UnitOfWorkImpl.j
ava:2767)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.remove(EntityManagerIm
pl.java:238)
at org.springframework.orm.jpa.JpaTemplate$7.doInJpa(JpaTemplate.java:280)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:191)
… 41 more
Result while deleting Emp Details::failed
Seth Geoghegan says:
Added on July 15th, 2008 at 3:24 pm[quote comment="7834"]thanks for the samples …
Error creating bean with name 'entityManagerFactory' defined in class path resource [jpa-datasource.xml]: Invocation of init method failed; nested exception is java.lang.LinkageError: Class org/xml/sax/Parser violates loader constraints
Caused by: java.lang.LinkageError: Class org/xml/sax/Parser violates loader constraints
which im not yet able to solve.
[/quote]
I too suffered for days with this problem. The solution that worked for me was to remove
from the configuration.
Good luck!
Maciek says:
Added on September 18th, 2008 at 4:13 amHello,
nice article. I've been wondering if you could help me with the following problem. Suppose I want to delete an Entree, which is still referenced by a Restaurant. How do I formulate the JPQL query that would remove a given Entree from all 'entrees' sets of the Restaurant entree? Queries like "DELETE FROM Restaurant.entrees e WHERE e = :entree" don't work.
Thanks in advance, Maciek
Maciek says:
Added on September 18th, 2008 at 4:16 am[quote comment="121755"]How do I formulate the JPQL query that would remove a given Entree from all 'entrees' sets of the Restaurant entree?[/quote]I ment Restaurant ENTITY, not entree, sorry!
ideyatech says:
Added on November 5th, 2008 at 10:15 pmi have an article regarding spring transactions on JPA
http://www.ideyatech.com/2008/09/troubleshooting-tips-spring-transactions-on-jpa/
Ondra Žižka says:
Added on December 25th, 2008 at 8:14 pmShouldn't there be "LocalContainerEntityManagerFactoryBean"?
Bruno says:
Added on May 28th, 2009 at 5:08 pmGreat article. Even after all this time, it is the clearest JPA 'getting started' document out there.
Unfortunately I am using Spring 2.5 and it looks like spring-jpa.jar and spring-mock.jar are no longer easy to find. Presumably they have been absorbed into spring.jar, and I see a bunch of *.orm.jpa.* classes there, but I get java.lang.ClassNotFoundException: org.springframework.orm.jpa.ContainerEntityManagerFactoryBean.
Any idea about where I might find the missing JARs? Or perhaps the Class has been replaced by something else?
Or… is there a version of your article updated for Spring 2.5?
Marten Deinum says:
Added on May 29th, 2009 at 1:50 am@Bruno that is clarified in the release notes of 2.5
Spring-jpa.jar == spring-orm.jar
spring-mock.jar == spring-test.jar
werwuifi says:
Added on June 8th, 2009 at 9:39 amhey,
great article, however im running into a NoSuchMethodError caused by org.slf4j.Logger.trace (in Hibernate ClassValidator.getDefaultResourceBundle()).
Anyone ever came across a similar problem?!?
That's my testContext.xml:
testContext used from within unit tests
<!– –>
<!– –>
<!– –>
<!–
–>
<!– –>
<!– –>
Thx for any suppport!
w
werwuifi says:
Added on June 8th, 2009 at 9:41 am<?xml version="1.0" encoding="UTF-8"?>
<beans>
<description>
testContext used from within unit tests
</description>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:META-INF/spring.properties.test"/>
</bean>
<!– uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file –>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"/>
</bean>
</property>
<!– <property name="loadTimeWeaver">–>
<!– <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>–>
<!– </property>–>
</bean>
<!– transaction manager for use with a single JPA EntityManagerFactory for transactional data access to a single datasource –>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource" />
<!–
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
–>
</bean>
<!–
- defines the dataSource as local test or development resource configured to properties from property placeholder
–>
<bean id="localDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
<!– <bean id="localDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">–>
<property name="driverClassName" value="${dataSource.driverClassName}" />
<property name="url" value="${dataSource.url}" />
<property name="username" value="${dataSource.username}" />
<property name="password" value="${dataSource.password}" />
<!– <property name="accessToUnderlyingConnectionAllowed" value="true" />–>
</bean>
<alias name="localDataSource" alias="dataSource"></alias>
</beans>
Tariq Ahsan says:
Added on September 16th, 2009 at 8:02 amI have been desperately searching in the internet and also has done numerous postings in both Spring Batch and Spring Data Access forums to get some examples codes where I am trying to use JpaTransactionManager, PersistenceAnnotationBeanPostProcessor, EntityManagerFactory etc.
Here's the xml file -
<![CDATA[{ isin : length(?)
<tx:annotation-driven transaction-manager="transactionManager"/
Here's one of the code using EntityManager object -
And here's the code -
@Repository
@Transactional
public class CustomerUpdateWriter implements ItemWriter {
...
//@PersistenceContext(unitName = "abc")
// Should I be using the above instead?
@PersistenceContext
protected EntityManager em;
@Transactional(readOnly = true)
public void write(List trades) {
log.debug("CustomerUpdateWriter : write : niin ");
try {
log.debug("Doing Query");
Query q = em.createQuery("select * from trade");
} catch (Exception ex) {
log.debug("In catch");
ex.printStackTrace();
}
...
And here's what I am getting in the console -
15:40:58,343 ERROR main CommandLineJobRunner:211 - Job Terminated in error:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:/jobs/tradeJob.xml]
Offending resource: class path resource [org/springframework/batch/sample/TradeJobFunctionalTests-context.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 135 in XML document from class path resource [jobs/tradeJob.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
…
15:40:58,343 ERROR main CommandLineJobRunner:211 – Job Terminated in error:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:/jobs/tradeJob.xml]
Offending resource: class path resource [org/springframework/batch/sample/TradeJobFunctionalTests-context.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 135 in XML document from class path resource [jobs/tradeJob.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
I am very new to Spring and trying just get a feel how to use EntityManager tto do database transactions to keep the Spring codes which would be integrated into our JBoss Seam Framework codes where EntityManager is been used.
Any help would be greatly appreciated.
Marco Massenzio says:
Added on January 2nd, 2010 at 4:58 pmI've got it all working nicely (JPA Spring MySQL JDBC driver etc.) but I have run into this weird problem and I'm just wondering whether anyone has seen this anywhere else: essentially, the VERY FIRST Junit test that I run, fails with the trace below; then, all the others work fine and pass without a problem.
It looks as if the very first time the JDBC driver from the mysql jar is not loaded, but I can't quite understand why (note, it does not matter which test runs first, or from which class/package, regardless, the first one will always fail).
Trace is here:
—
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'currencyService' defined in class path resource [com/ibw/stocks/beans.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'entityManagerFactory' threw exception; nested exception is Exception [TOPLINK-4002] (Oracle TopLink Essentials – 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: No suitable driver found for jdbc:mysql://fangorn:3306/stocks_dev
Error Code: 0
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessException details (1) are:
PropertyAccessException 1:
org.springframework.beans.MethodInvocationException: Property 'entityManagerFactory' threw exception; nested exception is Exception [TOPLINK-4002] (Oracle TopLink Essentials – 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: No suitable driver found for jdbc:mysql://fangorn:3306/stocks_dev
Error Code: 0
Caused by: Local Exception Stack:
Exception [TOPLINK-4002] (Oracle TopLink Essentials – 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: No suitable driver found for jdbc:mysql://fangorn:3306/stocks_dev
Error Code: 0
at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:305)
at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:102)
at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:184)
at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:582)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:280)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:229)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:93)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:126)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:120)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:375)
at $Proxy10.createEntityManager(Unknown Source)
at com.ibw.stocks.data.AbstractDao.setEntityManagerFactory(AbstractDao.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:821)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:645)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:78)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1126)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:287)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.test.jpa.AbstractJpaTests.runBare(AbstractJpaTests.java:229)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://fangorn:3306/stocks_dev
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:100)
… 49 more
—
The actual test is trivial:
/*
* For some mysterious reason, the very first test, when using JPA, fails because it
* cannot find the MySQL driver. All the others then pass.
*
* TODO (marco) find the root cause of this weird behaviour and fix it
*/
public void testDummy() {
assertTrue(true);
}
Any ideas?
Marco Massenzio says:
Added on January 2nd, 2010 at 6:08 pmUpdate:
Using loadtime weaving like this:
solves the problem.
However, this cannot be used in production, as GWT (Jetty) does not seem to pick the -javaagent VM option.
Damian Miranda says:
Added on July 7th, 2010 at 10:11 pmI've written a getting started tutorial of these two technologies (JPA and Spring) in spanish, you can visit on:
http://damianmigo.wordpress.com/2010/07/07/tutorial-jpa-hibernate-spring-orm-usando-eclipse/
JJ says:
Added on August 31st, 2010 at 5:24 amHello,
I am having an issue with JpaRestaurantDaoTests.
protected void onSetUpInTransaction() runs before every test.
So the 2nd test fails because of a duplicate primary key.
Also I notice the data isn't being rolled back after all the tests are done.
Do I need to have a onTearDownAfterTransaction() method [that was omitted from the blog code]as well or am I missing a setting?
Mohd Adnan says:
Added on September 20th, 2010 at 6:46 amin spring mvc when i submit data from my form then the exception occurs as given below.
The situation is like i have Entity class and i have taken anther Entity in it as part of relationship. when i send data to display it is working properly but when i post data after editing exception occurs. i have tried initbinding as well but doesn't work. help me…
rg.springframework.beans.NullValueInNestedPathException: Invalid property 'user' of bean class [org.mkcl.iforum.adnan.domain.UsersCredentials]: Value of nested property 'user' is null
at org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:453)
at org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:428)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:645)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:78)
at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:532)
at org.springframework.validation.DataBinder.doBind(DataBinder.java:434)
at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:147)
at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:108)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ArgumentsResolver.resolveArguments(AnnotationMethodHandlerAdapter.java:598)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:242)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:808)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:441)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:359)
at org.springframework.security.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.ui.ExceptionTranslationFilter.doFilterHttp(ExceptionTranslationFilter.java:101)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.providers.anonymous.AnonymousProcessingFilter.doFilterHttp(AnonymousProcessingFilter.java:105)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.ui.rememberme.RememberMeProcessingFilter.doFilterHttp(RememberMeProcessingFilter.java:116)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter.doFilterHttp(SecurityContextHolderAwareRequestFilter.java:91)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.ui.AbstractProcessingFilter.doFilterHttp(AbstractProcessingFilter.java:268)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.ui.logout.LogoutFilter.doFilterHttp(LogoutFilter.java:87)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.ui.SessionFixationProtectionFilter.doFilterHttp(SessionFixationProtectionFilter.java:61)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.context.HttpSessionContextIntegrationFilter.doFilterHttp(HttpSessionContextIntegrationFilter.java:235)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.securechannel.ChannelProcessingFilter.doFilterHttp(ChannelProcessingFilter.java:116)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:371)
at org.springframework.security.util.FilterChainProxy.doFilter(FilterChainProxy.java:174)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:183)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:138)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at test.HttpsCookieFilter.doFilter(HttpsCookieFilter.java:37)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:595)
paul says:
Added on November 15th, 2010 at 12:38 amcool, very informative post! i also wanna share this very spoon fed version of Spring Hibernate JPA combo
http://www.adobocode.com/spring/spring-with-hibernate-annotations
tnx
fatih says:
Added on December 2nd, 2010 at 8:10 amHie,
just one question : the "save" service is not tested, why not ?
dinesh says:
Added on April 7th, 2011 at 7:30 amHi all,
i am getting the error
org.springframework.dao.InvalidDataAccessApiUsageException: Unknown entity: com.dell.spring.jpa.domain.Persons; nested exception is java.lang.IllegalArgumentException: Unknown entity: com.dell.spring.jpa.domain.Persons………….
and my applicationcontext.xml is
<!–
–>
and my domain class is
package com.dell.spring.jpa.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "persons")
public class Persons {
@Id
@GeneratedValue
@Column(name = "P_ID")
private int P_ID;
@Column(name = "FIRSTNAME")
private String FIRSTNAME;
@Column(name = "LASTNAME")
private String LASTNAME;
@Column(name = "ADDRESS")
private String ADDRESS;
@Column(name = "CITY")
private String CITY;
@Column(name = "AGE")
private int AGE;
@Column(name = "GENDER")
private String GENDER;
public int getP_ID() {
return P_ID;
}
public void setP_ID(int p_ID) {
P_ID = p_ID;
}
public String getFIRSTNAME() {
return FIRSTNAME;
}
public void setFIRSTNAME(String fIRSTNAME) {
FIRSTNAME = fIRSTNAME;
}
public String getLASTNAME() {
return LASTNAME;
}
public void setLASTNAME(String lASTNAME) {
LASTNAME = lASTNAME;
}
public String getADDRESS() {
return ADDRESS;
}
public void setADDRESS(String aDDRESS) {
ADDRESS = aDDRESS;
}
public String getCITY() {
return CITY;
}
public void setCITY(String cITY) {
CITY = cITY;
}
public int getAGE() {
return AGE;
}
public void setAGE(int aGE) {
AGE = aGE;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
}
and my persistence.xml is
any body can help me.
thanks in advance
salish says:
Added on July 26th, 2011 at 8:34 amhi i'm new in spring and spring mvc
for an application i'm using the jpa the tables are by mysql and i created the entity class by netbeans,and for the spring binding in the jsp page we has to use the "" but the prblem is what about the multiple entity class ,means a class A inside that class B i want to bind the field in the class B but onsubmit action is not working for the case when i use b.email in the jsp
what is the problem please help me
thanks
in advance