How to connect OpenJPA, Spring and PostgreSQL? - java

I'm trying to connect my PostgreSQL db with OpenJPA and Spring.
Here is my Spring Context file. It contains MVC part and TX.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ctx="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<ctx:annotation-config/>
<ctx:component-scan base-package="de.alex.web.pag"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="pagPU"/>
<property name="persistenceXmlLocation" value="/META-INF/persistence.xml"/>
<property name="jpaVendorAdapter" ref="openJpaVendorAdapter"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/box"/>
<property name="username" value="postgres"/>
<property name="password" value="bob"/>
</bean>
<bean id="openJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="POSTGRESQL"/>
<property name="databasePlatform" value="org.apache.openjpa.jdbc.sql.PostgresDictionary"/>
</bean>
</beans>
Here is my persistence.xml in the /properties/META-INF/ folder:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pagPU" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>de.alex.web.pag.entity.Category</class>
<class>de.alex.web.pag.entity.Order</class>
<class>de.alex.web.pag.entity.Product</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/box"/>
<property name="openjpa.jdbc.DBDictionary" value="postgres"/>
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="openjpa.ConnectionUserName" value="postgres"/>
<property name="openjpa.ConnectionPassword" value="bob"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
</properties>
</persistence-unit>
</persistence>
When I try to run this simple script in my IDE I receive this exception:
[2014-09-26 17:16:43] java.lang.RuntimeException: <openjpa-2.3.0-r422266:1540826 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter "select c from Category c where c.id = 1". Error message: The name "Category" is not a recognized entity or identifier. Known entity names: []
at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:119)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:197)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:167)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:242)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:212)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:205)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.access$200(JPQLExpressionBuilder.java:80)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.populate(JPQLExpressionBuilder.java:2428)
at org.apache.openjpa.kernel.jpql.JPQLParser.populate(JPQLParser.java:61)
at org.apache.openjpa.kernel.ExpressionStoreQuery.populateFromCompilation(ExpressionStoreQuery.java:162)
at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:673)
at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:654)
at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:620)
at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:682)
at org.apache.openjpa.kernel.QueryImpl.compile(QueryImpl.java:589)
at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:997)
at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:979)
at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:102)
in RemoteEntityManagerImpl.createQuery(RemoteEntityManagerImpl.java:39)
in RemoteUtil.executeWithClassLoader(RemoteUtil.java:167)
in RemoteUtil$2$1.invoke(RemoteUtil.java:102)
at com.sun.proxy.$Proxy151.createQuery(Unknown Source)
in JpaEngine.createQuery(JpaEngine.java:104)
Seems I missed something important when I was configuring Spring context or JPA context.
UPDATE
My entity class:
#Entity
#Table(name = "category")
public class Category {
#Id
#SequenceGenerator(name = "pk_seq", sequenceName = "category_table_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_seq")
private Integer id;
#Column(name = "name")
private String name;
public Category() {
}
// getters and setters ommited
}
UPD2
Now I get this exception:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is <openjpa-2.3.0-r422266:1540826 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "
de.alex.web.pag.entity.Category
de.alex.web.pag.entity.Product
de.alex.web.pag.entity.Order".

Your issue here is that by default OpenJPA uses bytecode (compile time) enhancement of persistent entities rather than say, for example, Hibernate's approach of runtime proxies.
You therefore need to either:
at compile time enhance the persistent classes. See: http://openjpa.apache.org/entity-enhancement.html. If you are using Maven configure the plugin in your POM. If you are also using Eclipse configure the plugin to save having to run a full 'mvn clean install' on every change to your persistent classes.
http://openjpa.apache.org/openjpaeclipseenhancementbuilder.html
or
enable runtime enhancement: http://openjpa.apache.org/runtime-enhancement.html

Related

I am stuck with different combinations of spring.config, persistence.xml and pom files

I am looking for a working version of configuration for spring boot application for hibernate 4 and mysql.
I am getting the following error with my configuration since yesterday:( :
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource [spring-config.xml]: Invocation of init method failed; nested
exception is java.lang.IllegalStateException: JPA PersistenceProvider
returned null EntityManagerFactory - check your JPA provider setup!
This is my persistence.xml file
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="my-pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.PersistenceProvider</provider>
<class>com.crossover.trial.travelmanagementportal.model.Order</class>
<class>com.crossover.trial.travelmanagementportal.model.User</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="12345678"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/travelmanagement" />
<property name="hibernate.default_schema" value="travelmanagement" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
And this is my spring.config file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/tx">
<context:annotation-config />
<context:property-placeholder location="classpath:application.properties" />
<context:component-scan base-package="com.crossover.trial.travelmanagementportal" />
<!-- For #Transactional annotations -->
<!-- This makes Spring perform #PersistenceContext/#PersitenceUnit injection: -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- Drives transactions using local JPA APIs -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="my-pu" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/travelmanagement" />
<property name="username" value="root" />
<property name="password" value="xxxx" />
</bean>
<bean id="currentUserDetailsService" class="com.crossover.trial.travelmanagementportal.service.CurrentUserDetailsService" />
<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="currentUserDetailsService" />
<property name="passwordEncoder" ref="encoder" />
</bean>
</beans>
If you use
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
in your pom.xml then you can simply set up you connection to db with:
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=
in application.properties
There is an easy way to generate a starter project with spring boot.

Trouble with Spring Data Repositories

It has been 2 days i am trying to work with Spring Data repositories and trying to setup a simple repository.
I have simple UserRepository using CrudRepository
I have my entity class
And here is my XML in which the highlighted line is giving me error in web browser
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<jpa:repositories base-package="com.mydata"/>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="test"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.mydata"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
</beans>
When i access the controller in which i initilize this beans class i get following error in web browser
Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.orm.jpa.vendor.Database' for property 'database'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.orm.jpa.vendor.Database] for property 'database': no matching editors or conversion strategy found
And this error occurs because of line in XML property name="database" value="test"
Shahzad
The indicated in the JavaDoc the database property takes the database type, not the name.
In general, I suggest to rather look at Spring Boot and its JPA support (find a guide here) as it svaes you from all the boilerplate configuration setup.
Did you try MYSQL database value? I think Spring should convert it implicitly to Database.MYSQL
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
Or Spring Boot bean definition
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}

Spring IllegalStateException: A JTA EntityManager cannot use getTransaction()

So after a big refactoring project, I am left with this exception and am unsure as how to correct it. It's dealing with some code that I did not write and I am unfamiliar with how it all works. There are other questions out there dealing with this exception, but none seem to fit my situation.
The class which uses EntityManager is SpecialClaimsCaseRepositoryImpl:
package com.redacted.sch.repository.jpa;
//Imports
#Repository
public class SpecialClaimsCaseRepositoryImpl extends SimpleJpaRepository<SpecialClaimsCaseDto, SpecialClaimsCaseDto.Id> implements SpecialClaimsCaseRepository{
#PersistenceContext(unitName = "schManager")
private EntityManager em;
//Some autogenerated methods
public void setEntityManager(EntityManager em) {
this.em = em;
}
public EntityManager getEntityManager() {
return em;
}
}
Persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="schManager">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/SCH_DS</jta-data-source>
<class>com.redacted.sch.domain.model.SpecialClaimsCaseDto</class>
<properties>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.dialect" value="com.bcbsks.hibernate.dialect.DB2Dialect" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.generate_statistics" value="false" />
<property name="hibernate.jdbc.use_scrollable_resultset" value="true" />
</properties>
</persistence-unit>
</persistence>
sch_model_spring.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.redacted.repository.jpa,
com.redacted.sch.domain.model,
com.redacted.sch.repository.jpa,
com.redacted.sch.service,
com.redacted.sch.service.impl"/>
<tx:annotation-driven />
<tx:jta-transaction-manager />
<!-- Data source used for testing -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2:redacted.redacted.com" />
<property name="username" value="redacted" />
<property name="password" value="redacted" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="schManager" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
And here's my project structure:
>
Here's a portion of the stack trace, with the full trace at this fpaste
Caused by: java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:985)
at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:67)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 80 more
I'm a total noob here, so if any other information is needed just ask and I'll update.
Thanks for all the help!
The problem is your configuration. You have hibernate configured for JTA.
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
Whereas you are using local transactions instead of distributed transactions.
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
You have 2 possible solutions
remove the JpaTransactionManager and replace it with a JTA transaction manager
remove the remove the hibernate.transaction.manager_lookup_class from the hibernate settings.
If you don't really need distributed transactions option 2 is the easiest, if you need distributed transactions simply adding <tx:jta-transaction-manager /> will setup a proper JTA tx manager for your environment. Remove the definition for the JpaTransactionManager.
Update:
Your configuration is flawed in 2 ways.
Your EntityManager configuration already contains a jndi lookup for the datasource, which you override in your applicationContext by configuring a local datasource
You have both a <tx:jta-transaction-manager /> and JpaTransactionManager which one do you want to use? At the moment the latter is overriding the first one.
Create 2 seperate configurations one for local testing and one for production using JTA en JNDI lookups. (Preferable your testing code only overrides the beans necessary).
Use WebSphereTransactionManagerLookup for the transaction manager lookup in Hibernate
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereTransactionManagerLookup" />
and remove your current transaction manager and replace it with the WebSphereUowTransactionManager.
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/>
for your transaction manager lookup in Spring.
See IBM Websphere and Spring docs
for more in depth documentation.

Spring JPA Hsqldb persistence

I'm new to spring so I don't know if everything is configured correctly. Though I use the spring IDE and a unittest provided to be correct.
I'm having a User class
#Entity
#NamedQuery(name="findUser4Email",
query="SELECT * " +
"FROM User " +
"WHERE email = :userEmail")
public class User extends AbstractNamedDomain {
private String name;
private String email;
private String password;
...
I want to keep this class persistent with a DB. I use hsqldb to send queries to my db and so on.
Now I have a DAO layer for my user which looks like this :
public class UserManager implements IUserManager {
#PersistenceContext
private EntityManager em;
public User findUser4Email(String email) {
return (User) em.createNamedQuery("findUser4Email").setParameter("userEmail",
email).getSingleResult();
}
public User storeUser(User user) {
//User u = em.merge(user);
em.persist(user);
return user;
}
...
my beans look like this :
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="BankingWeb" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<property name="databasePlatform" value="${hibernate.dialect}" />
</bean>
</property>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean name="AccountManager" class="ssel.banking.dao.jpa.AccountManager" />
<bean name="UserManager" class="ssel.banking.dao.jpa.UserManager" />
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
When I try to store a User in a unittest (just by calling the store(User) from the dao the test fails. Nor do I see any table created in my DB when I look at it with hsqldb. What is wrong my code ? Or what do I miss?
this is what my datasourcebean looks like
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
You have to define a DataSource bean like this:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.0.0.1:3306/yourDB"/>
<property name="username" value=""/>
<property name="password" value=""/>
</bean>
(Or a JNDI lookup)
<jee:jndi-lookup jndi-name="jdbc/datasource" id="dataSource" />
You can follow this tutorial to help you setting everything up.

UserType / Hibernate / JodaMoney error : PersistentMoneyAmount requires currencyCode to be defined as a parameter

I'm using UserType 3.0.0.RC1 to map JodaMoney to Hibernate.
I'm stuck with an error when the SessionFactory initialises:
PersistentMoneyAmount requires currencyCode to be defined as a
parameter, or the defaultCurrencyCode Hibernate property to be defined
I'm sure I must have some configuration issue — here's the relevant snippets.
Persistence.xml:
<persistence-unit name="spring-jpa">
<properties>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="jadira.usertype.autoRegisterUserTypes" value="true"/>
</properties>
</persistence-unit>
The relevant spring config:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.mangofactory.concorde</value>
<value>com.mangofactory.moolah</value>
</list>
</property>
<property name="persistenceUnitName" value="spring-jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
Any tips on what I'm missing?
I ended up solving this using the following configuration in my persistence.xml:
<persistence-unit name="spring-jpa">
<properties>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="jadira.usertype.autoRegisterUserTypes" value="true"/>
<property name="jadira.usertype.currencyCode" value="AUD"/>
<property name="jadira.usertype.seed" value="org.jadira.usertype.spi.shared.JvmTimestampSeed"/>
</properties>
</persistence-unit>
The tricky part is that I needed to provide a jadira.usertype.seed in order for the jadira.usertype.currencyCode to be detected.
if you're looking for an annotation based solution, you may try this
#Type(type = "org.jadira.usertype.moneyandcurrency.joda.PersistentMoneyAmount", parameters = { #Parameter(name="currencyCode", value="USD") })
private Money price;
found here
Email Archive: usertype-discuss (read-only)
Regarding the need to configure seed - this is due to a bug in 3.0.0-RC1 and will be fixed in future.

Categories

Resources