I'm trying to test an application which uses SpringMVC and Hibernate with MySQL. I tried using HSQLDB but since the syntax is not the same as MySQL the queries may not work, so I decided to go to H2.
The problem is that when I run it it says "Table MAILCONFIG not found", and if I created on the INIT syntax it says that already exists.
I have configured a simple test that doesn't do anything, I only want it to run.
I have the following files:
ServiceTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"file:src/test/resources/applicationContext.xml"})
#Transactional
#WebAppConfiguration
public class ServiceTest {
private static DataSource ds;
#BeforeClass
public static void setUpConnection(){
ds = new DataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:mem:testDB");
ds.setUsername("sa");
ds.setPassword("");
HibernateConfiguration.dataSourceTest(ds);
}
#AfterClass
public static void cleanConnection(){
HibernateConfiguration.dataSourceTest(null);
}
}
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="testingSetup" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
</bean>
<context:component-scan base-package="com.adistec" />
<context:annotation-config/>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="testingSetup" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:mem:testDB;DB_CLOSE_DELAY=-1;MODE=MySQL" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
MailConfig.java
#Entity
public class MailConfig {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
#Column
String host;
}
I specify the Hibernate configuration in the test because the application uses java classes and not the XML files.
Can anyone help me with this? Or if there is an easier way to test it with java classes is welcome too, I couldn't find out a solution yet.
I want it to work locally and then it has to work with jenkins too, so it can create things that can't do on the VM.
Thank you!
Seems #Table annotation is missing in your MailConfig class.
You can find full working example using spring, hibernate and h2 database from http://mycuteblog.com/h2-database-example-hibernate-spring-boot/
Add #EntityScan(basepackage="com.entity") Annotation in main class
Related
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.test.dao.CustomerDaoImpl</class>
<class>com.test.data.Customer</class>
<class>com.test.dto.CustomerDto</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
</properties>
</persistence-unit>
Class where I am using it:
public class CustomerDaoImpl implements CustomerDao {
#PersistenceContext(unitName = "persistenceUnit")
private EntityManager entityManager;
#Transactional
public List<CustomerDto> getCustomers() {
List<CustomerDto> customers = null;
List<Customer> cust = new ArrayList<Customer>();
Query q = entityManager.createQuery(
"SELECT c"
+ " FROM Customer c ");
EDIT ADDING SPRING-SERVLET.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<context:spring-configured />
<context:component-scan base-package="com.test"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="username" value="root" />
<property name="password" value="password" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="3" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/js/" />
<property name="suffix" value=".js" />
</bean>
After I tested this I recognized that Netbeans is giving me error in the class CustomerDaoImpl and it is saying that: "Class is listed in the persistence.xml but it is not annotated". What is correct annotation in this case?
I can see from log that there is correct entitymanager for pu: Closing JPA EntityManagerFactory for persistence unit 'persistenceUnit' and I am creating the dao like that:
#Autowired
CustomerDao customerDao;
When using #autowired annotation, customerDao is null, so I tried to create dao with
customerDao = new CustomerDaoImpl();
and then entitymanager is NULL.
In the persistence.xml you don't need
<class>com.test.dao.CustomerDaoImpl</class>
<class>com.test.dto.CustomerDto</class>
use only
<class>com.test.data.Customer</class>
I've got a question to Spring, hibernate and testng.
I am developing an app and try to write a transactional unit test. The question is how could I rollback my database operation when my buissnes method is marked as "transactional"?
The code:
#Test
#ContextConfiguration(locations = { "classpath:applicationContext.xml" })
#TransactionConfiguration(defaultRollback = true)
public class SampleTest extends
AbstractTransactionalTestNGSpringContextTests {
#Autowired
private AuthorDao authorDao;
#BeforeTest
void createAppCtx() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"/applicationContext.xml");
}
#Test
void testStg() {
Person person = new Author();
person.setFirstName("Edward");
person.setLastName("Kowalski");
authorDao.createAuthor(person);
}
In my authorDao I've following method:
#Repository
#Transactional
public class AuthorDao {
#PersistenceContext
private EntityManager entityManager;
public AuthorDao() {
}
public AuthorDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Author createAuthor(Person author) {
entityManager.persist(author);
return (Author) author;
}
}
If the application context is needed, I can also attach it.
So as you can see the buisness method is transactional so there is a commit after calling. So point is how to avoid commit in the test class?
Is it possible?
Many thanks for help.
EDIT:
applicationContext:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
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-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="pl.hs" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTxManager" />
<beans>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:project.properties" />
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${hibernate.connection.driver_class}"
p:url="${hibernate.connection.url}"
p:username="${hibernate.connection.username}"
p:password="${hibernate.connection.password}" />
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="myDataSource" />
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="persistenceUnitName" value="pl.hs" />
</bean>
<bean id="myTxManager" name="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
<!-- <property name="dataSource" ref="myDataSource" /> -->
</bean>
</beans>
</beans>
Persistnce.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
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">
<persistence-unit name="pl.hs"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class> myJavaClasses </class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"></property>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create"></property>
</properties>
</persistence-unit>
Add #Transactional to the test method too so that the TransactionConfiguration applies.
The TransactionConfiguration starts a new transaction when the test starts and it rolls it back at the end of the test.
So you don't have to do anything special to roll the current transaction.
If you wanted to add another logic unit after:
authorDao.createAuthor(person);
then you'd better write another test method.
Each test should verify one and only one behavioural unit. If you have several responsibilities tested in a single test method, then you should break those into several tests.
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
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.
How can I configure Hibernate so it maps beans to some existing tables?
P.S: Each table should correspond with an entity.
Edit: Here is how I used Hibernate with autogenerated tables (taken from a web application). I'm still not clear on how to make the transition to some explicit mapping.
Example Entity bean
#Entity
#Table(name = "t1_category")
// PK is replaced by Long
// See generic definition in abstract class
public class Category extends BaseEntity<Long> {
#Column(name="check_rsv")
private String check;
#Column(unique = true)
private String name;
private static final long serialVersionUID = 1L;
public String getCheck() {
return this.check;
}
public void setCheck(String check) {
this.check = check;
}
public String getName() {
return this.name;
}
public void setName(String title) {
this.name = title;
}
}
applicationContext.xml/Spring
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="***" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPersistenceUnit" />
</bean>
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<tx:annotation-driven/> <!-- This apparently scans for annotations from the base-package value -->
</beans>
Persistence.xml
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="myPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/***?autoReconnect=true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="***"/>
<property name="hibernate.connection.username" value="***"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
(What do you mean "fills in"? Map beans to tables? Then:)
Old way: create Hibernate *.hbm.xml per table/entity. Nothing extraordinary, did it in past.
New way: create beans, mark them up with the Hibernate annotations.
New new way: use JPA annotations for portable mapping and Hibernate as JPA implementation.
Hibernate annotations allow you to specify the table and column names. I'm adding the batch size and cache option as an extra, but that's not required for your question.
#Entity
#Table(name="BLAH")
#BatchSize(size=20)
#Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
public class Blah{
#Id
protected String theID;
#Column(name="MEH")
protected int meh;
}
Have a look at all the options in #Table #Column #Index and the #JoinColumn option for the one-to-many et al. relationships.