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.
Related
I am trying to unit test my service classes in a spring-hibernate application.
public class UserServiceTest extends SpringAwareTest {
#Autowired
#Qualifier("userService")
private UserService userSvc;
#Autowired
#Qualifier("roleService")
private RoleService roleSvc;
...
}
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="/application-test-context.xml")
#Transactional
//#SpringApplicationConfiguration
#SpringBootTest
#Configurable
public abstract class BaseSpringAwareTest {
....
}
My spring context file is as follows:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<!-- import resource="classpath:/applicationContext.xml"/ -->
<context:component-scan base-package="com.olp"/>
<tx:annotation-driven />
<jpa:repositories base-package="com.olp.jpa" entity-manager-factory-ref="entityManagerFactory"/>
<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="persistenceUnitManager" ref="persistenceUnitMgr"/>
<property name="jpaDialect" ref="jpaDialect"/>
</bean>
<bean id="persistenceUnitMgr" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation" value="classpath:persistence-test.xml"/>
<property name="defaultPersistenceUnitName" value="productHubTest"/>
<property name="packagesToScan">
<array value-type="java.lang.String">
<value>com.olp.jpa</value>
</array>
</property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
...
</beans>
I am getting this exception while executing the JUnits -
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: UserEntity is not
mapped [SELECT t FROM UserEntity t JOIN FETCH t.roles ORDER BY
t.userName ASC] at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at
org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
at
org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:729)
at
org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ...
My entity classes are in child packages of the top level component scan mentioned - "com.olp"
package com.olp.jpa.domain.docu.um.model;
...
#Entity
#Table(name = "trl_users")
#Cacheable(true)
#NamedQueries({
#NamedQuery(....)
})
// ...
public class UserEntity extends MultiTenantLifeCycleEntity {
// ...
}
package com.olp.jpa.common;
#MappedSuperclass
public class MultiTenantLifeCycleEntity {
// ...
}
Couldn't identify the root cause. Any pointers will be highly appreciated.
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
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
i have the following problem. I use Spring and JPA (Hibernate) to persist Data in a Database. But i have an Error during saving the Data. My Database keeps empty after I create a new User. Here are the important files:
UserDao Interface:
import java.util.List;
public interface UserDao {
public User findById(Integer id);
public List<User> findAll();
public User findByEmail(String email);
public void save(User user);
}
UserDaoImpl:
#Repository
public class UserDaoImpl implements UserDao {
#PersistenceContext
private EntityManager em;
#Override
public User findById(Integer id) {
return em.find(User.class, id);
}
#SuppressWarnings("unchecked")
#Override
public List<User> findAll() {
return (List<User>)em.createQuery("from User u").getResultList();
}
#Override
public User findByEmail(String email) {
User user = null;
try
{
user = (User)em.createQuery("from User u where u.email = ?1").setParameter(1, email).getSingleResult();
}
catch(NoResultException e){}
return user;
}
#Override
#Transactional
public void save(User user) {
em.persist(user);
}
}
Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd" default-autowire="byName">
<context:component-scan base-package="de.bht.swp.lao.ocp" />
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/ocp" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ocpPU" />
<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.MySQL5InnoDBDialect" />
</bean>
</property>
<property name="loadTimeWeaver" ref="loadTimeWeaver"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<context:load-time-weaver weaver- class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</beans>
persistence.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="ocpPU">
</persistence-unit>
When i create a new User i get the following Errorlog:
14:42:05,703 DEBUG [org.hibernate.event.def.AbstractSaveEventListener] - delaying identity-insert due to no transaction in progress
14:42:05,704 DEBUG [org.springframework.orm.jpa.EntityManagerFactoryUtils] - Closing JPA EntityManager
14:42:05,707 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Rendering view [org.springframework.web.servlet.view.RedirectView: unnamed; URL [/user/login.htm]] in DispatcherServlet with name 'dispatcher'
14:42:05,708 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
I think its a Trancation Error.
I´v already spent so much time in other channels. What means "delaying identity-insert due to no transaction in progress"?
thanks for the help beforehand
greeting
The problem is the #Repository in UserDaoImpl, remove it and make a bean
<bean id="userDao" class="de.bht.swp.lao.ocp.user.UserDaoImpl" />
in your Context.xml
I can't explain this behavior but this is the reason.