I am working on a java application using JSF and hibernate and the database is oracle.
this is my entity class---------
#Entity
#Table(name="docUpload")
#SequenceGenerator(name="seqGen",sequenceName="docseq")
public class DocDetailsEntity {
#Id
#GeneratedValue(generator="seqGen",strategy=GenerationType.SEQUENCE)
private Integer docId;
private String docName;
private String docDesc;
private String userId;
#Lob
private Clob doc;
table scrips--------
create table docUpload
(
docId number(10) primary key,
docName varchar2(50) not null,
docDesc varchar2(100),
userId varchar2(10) not null,
doc clob not null
);
CREATE SEQUENCE docseq
START WITH 100
INCREMENT BY 1
NOCACHE
NOCYCLE;
hibernate.cfg.xml-----
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- hibernate dialect -->
<property name="hibernate.dialect"> org.hibernate.dialect.OracleDialect </property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#xxxxx:1521:xx</property>
<property name="hibernate.connection.username">xxxx</property>
<property name="hibernate.connection.password">xxxx</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Automatic schema creation (begin) === -->
<property name="hibernate.hbm2ddl.auto">none</property>
<!-- Simple memory-only cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- <property name="show_sql">true</property> -->
<mapping class="entity.DocDetailsEntity"/>
</session-factory>
</hibernate-configuration>
but i am getting this error when i am trying to persist the entity into the db
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
.
.
.
.
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
please suggest me a solution
Could you please try to write as
#Table(name="docUpload",schema = "schemaName" )
#SequenceGenerator(name="seqGen",sequenceName="schemaName.seqName")
Related
I was facing an issue of inserting data in database where STOCK_ID is identity and STOCK_NAME is string. While inserting the data in database it shows an exception which has mentioned below. Kindly guide me to rectify the issue.
Hibernate: insert into mkyongdb.system.STOCK (STOCK_NAME) values (?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.mkyong.user.Stock]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at com.mkyong.common.App.main(App.java:45)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00926: missing VALUES keyword
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57)
... 16 more
Stock.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.mkyong.user.Stock" table="STOCK" catalog="mkyongdb">
<id name="stockId" type="java.lang.Integer">
<column name="STOCK_ID" />
<generator class="identity" />
</id>
<property name="stockName" type="string">
<column name="STOCK_NAME" length="10" />
</property>
<!-- <one-to-one name="stockDetail" class="com.mkyong.user.StockDetail"
cascade="save-update"></one-to-one> -->
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#127.0.0.1:1521/xe</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.default_schema">system</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping resource="com/mkyong/user/DBUser.hbm.xml"></mapping>
<mapping resource="com/mkyong/user/Stock.hbm.xml" />
<mapping resource="com/mkyong/user/StockDetails.hbm.xml" />
</session-factory>
</hibernate-configuration>
Stock.java
package com.mkyong.user;
public class Stock implements java.io.Serializable {
private Integer stockId;
private String stockName;
//private StockDetail stockDetail;
/*public StockDetail getStockDetail() {
return stockDetail;
}
public void setStockDetail(StockDetail stockDetail) {
this.stockDetail = stockDetail;
}*/
public Stock() {
//super();
// TODO Auto-generated constructor stub
}
public Stock(Integer stockId, String stockName) {
super();
this.stockId = stockId;
this.stockName = stockName;
}
public Integer getStockId() {
return stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
}
Main.java
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
stock.setStockName("sam");
session.save(stock);
session.getTransaction().commit();
Create Query:
CREATE TABLE STOCK
(
STOCK_ID numeric(10) not null,
STOCK_NAME varchar2(50) not null,
CONSTRAINT STOCK_PK PRIMARY KEY (STOCK_ID)
);
I think mkyongdb is your schema which has table named STOCK. So,
use mkyongdb.STOCK instead of mkyongdb.system.STOCK in the
insert statement.
STOCK_ID is a mandatory field and missing in the insert statement.
( By the way, If you use Oracle12c this field may not be included in the insert statement provided that defined as STOCK_ID numeric(10) GENERATED by default on null as IDENTITY in the create table DDL statement directly without need of any other mechanism like trigger. If you have version prior to 12c, a before insert trigger may be created which includes :new.STOCK_ID := seq_stock_id.nextval; statement, where seq_stock_id is a sequence )
I need to be able to store database config properties in an external file that well be used by the application jar and include it in form of jstl expressions. (like : ${password} etc.)?
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.DB2Dialect</property>
<property name="connection.url">jdbc:db2://localhost:50001/svntools</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
-->
<property name="show_sql">true</property>
<mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.BrancheEntity"/>
<mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.RevisionEntity"/>
<mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.ProjectEntity"/>
<mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.StatistiqueEntity"/>
<mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.DomaineEntity"/>
</session-factory>
</hibernate-configuration>
SpringConfig.xml file
<?xml version="1.0" encoding="UTF-8"?>
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">
<bean id="projectDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.ProjectDAOImpl">
</bean>
<bean id="reportDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.ReportDAOImpl" />
<bean id="brancheDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.BrancheDAOImpl" />
<bean id="domaineDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.DomaineDAOImpl" />
<bean id="svnKitDa"
class="fr.gouv.education.sirhen.svnreporting.domaine.DA.impl.SVNKitDAImpl" />
<bean id="RevisionServicesBean"
class="fr.gouv.education.sirhen.svnreporting.domaine.impl.RevisionsServicesImpl">
<property name="svnKitDa" ref="svnKitDa" />
<property name="brancheDAO" ref="brancheDAO" />
</bean>
<bean id="parser" class="fr.gouv.education.sirhen.svnreporting.transvers.utils.ParserImpl" />
<bean id="reportServices"
class="fr.gouv.education.sirhen.svnreporting.service.impl.ReportServicesImpl">
<property name="reportDAO" ref="reportDAO" />
<property name="brancheDAO" ref="brancheDAO" />
<property name="projectDAO" ref="projectDAO" />
<property name="parser" ref="parser" />
</bean>
<bean id="projectServices"
class="fr.gouv.education.sirhen.svnreporting.service.impl.ProjectServicesImpl">
<property name="projectDAO" ref="projectDAO" />
</bean>
<bean id="domaineServices"
class="fr.gouv.education.sirhen.svnreporting.service.impl.DomaineServicesImpl">
<property name="domaineDAO" ref="domaineDAO" />
</bean>
<bean id="generator"
class="fr.gouv.education.sirhen.svnreporting.domaine.generatorDocServices.impl.GeneratorDocServiceImpl" />
The class that use the session:
package fr.gouv.education.sirhen.svnreporting.persistance.impl;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import fr.gouv.education.sirhen.svnreporting.persistance.ProjectDAO;
import fr.gouv.education.sirhen.svnreporting.persistance.eo.ProjectEntity;
public class ProjectDAOImpl implements ProjectDAO {
private static final String Location_Hibernate =
"resources/hibernate.cfg.xml";
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void addProject(ProjectEntity project) {
File hibernatePropsFile = new File(Location_Hibernate);
Session session=new Configuration().configure(hibernatePropsFile).buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
session.saveOrUpdate(project);
t.commit();
session.close();
}
public List<ProjectEntity> getProjects() {
File hibernatePropsFile = new File(Location_Hibernate);
Session session=new Configuration().configure(hibernatePropsFile).buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
List<ProjectEntity> projects= session.createCriteria(ProjectEntity.class).list();
t.commit();
session.close();
return projects;
}
public List<String> getProjectsNames() {
File hibernatePropsFile = new File(Location_Hibernate);
Session session=new Configuration().configure(hibernatePropsFile).buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
List<ProjectEntity> projects= session.createCriteria(ProjectEntity.class).list();
t.commit();
session.close();
List<String> ProjectsNames=new LinkedList<String>();
for( ProjectEntity projet : projects)
{
ProjectsNames.add(projet.getName());
}
return ProjectsNames;
}
}
An alternate approach is you can directly use hibernate.properties file instead of hibernate.cfg.xml.
But if you want to use another file then hibernate.properties file then please refer link given below:
How to read database configuration parameter using properties file in hibernate
Still, if you want to read properties file separate then you can read with normal java code to read properties file from class path or relative file path and set those properties on environment using ConfigurableEnvironment of spring.
Edited Answer
If you want to read properties file outside of your application (jar) then you can read properties file programmatically from relative file path.
I have provided one answer earlier and that was the same situation for read properties file, You can follow my Edited answer from there.
Spring Boot embedded Tomcat not loading external properties file in ApplicationListener
Now You can use System properties or Environment properties to store properties loaded earlier from relative file path and then it will available any where in the application.
#Autowired
private ConfigurableEnvironment myEnv;
or
System.setProperty ("propertyName", "propertyValue");
An issue I'm unsure of atm, I have hibernate handling my logins through a user table. If this table is manipulated whilst the app is running, no change takes place on the login side of things (however they do on tables, I'm using ZK for that and can see the changes correctly).
So if I log in with:
admin password
Then change the password to newpassword
I have to clean & build the app, then run it before the change takes place for the login.
So in other words I think it only checks the user table data once, keeps it somewhere?
Anyway code I think might help:
snippet of applicationContext-security.xml
<beans:bean id="sesFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<beans:property name="configLocation">
<beans:value>classpath:\hibernate.cfg.xml</beans:value>
</beans:property>
</beans:bean>
<beans:bean id="userDAO" class="login.UserLoginDAOImpl">
<beans:property name="sessionFactory" ref="sesFactory"></beans:property>
</beans:bean>
<beans:bean id="userService" class="login.UserLoginService">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userService">
<!--<password-encoder hash="sha" />-->
</authentication-provider>
</authentication-manager>
hibernation.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="contacts.Contacts" />
<mapping class="login.Users" />
</session-factory>
</hibernate-configuration>
UserLoginDaoImpl:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
/**
* The Class UserLoginDAOImpl
*/
public class UserLoginDAOImpl implements UserLoginDAO {
/** The hibernate template. */
private HibernateTemplate hibernateTemplate;
/**
* Sets the session factory.
*
* #param sessionFactory
* the new session factory
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Override
public Users loadUserByName(String name) {
if (name != null && !name.equals("")) {
List<Users> usr = hibernateTemplate
.find("from Users where username ='" + name + "'");
System.out.println(usr.get(0));
if (usr.size() == 1) {
return usr.get(0);
} else {
System.out.println("USER SIZE IS INCORRECT");
return null;
}
} else {
return null;
}
}
}
I'm by no means an expert in Hibernate, but I think that
<property name="current_session_context_class">thread</property>
line is unnecessary and affects the behavior of transaction manager: See spring, hibernate and declarative transaction implementation: there is no active transaction
P.S. Spring manages transactions via AnnotationSessionFactoryBean and possibly something interesting happens inside your UserLoginDAOImpl and UserLoginService classes.
Trough the entity manager I'm tryng to persist the entity in the database but I don manage to persists it. Here goes my configuration.
I have this Entity:
#Entity
#Table(name = "User")
public class UserModel implements Serializable, ModelItem {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(nullable = false)
private String username;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String name;
private String surname;
private String notes;
private String cellphone;
#Column(nullable = false)
private String email;
private Boolean enabled;
//get and set methods
.....
}
and my import bean that does the persistence:
#Repository
public class ImportServiceImpl implements ImportService {
#PersistenceContext
protected EntityManager entityManager;
#Transactional
public boolean importExample() {
User u= new User();
u.setUsername("username");
u.setPassword("password");
u.setName("name");
u.setEmail("email");
entityManager.persist(u);
}
}
The spring configuration for the entity manager and the db connction:
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" /> <!-- Prints used SQL to stdout -->
<property name="generateDdl" value="true" /> <!-- Generates tables. -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
and my persistence.xml
<?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_1_0.xsd"
version="1.0">
<persistence-unit name="application" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/testdata"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
So when I run my example I don't get any error but entity is not persisted. I also tryied to add entityManager.flush() after persist but in this case i get this error:
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:793)
So I'm thinking my Transactional bean is not well binded to the method, but I can not understand the reason. Somebody knows why?
I also noticed in STS that for this transaction are generated 2 beans with same data it looks strange (I don't know if it is a bug of STS or is a problem in my configuration that creates 2 beans):
I've faced an issue similar to the one described.
I found the problem in incorrect usage of #Transactional notation, in particular I've wrongly used javax.transaction.Transactional instead of org.springframework.transaction.annotation.Transactional
A detailed description of the difference can be found here at javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional
Maybe try specifying the persistence unit name "application" in your #PersistenceContext annotation?
#PersistenceContext(unitname = "application")
I also faced the same issue, as Repoker said Persistence provider is ok but my transaction manager was screwed. I added transactionManager bean in my application-config.xml like this
<bean id="transactionManager" cass="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEntityManagerFactory" />
</bean>
and It works fine now!!
you can use entityManager.flush() just after persist and merge it could solve your problem
You have <tx:annotation-driven /> twice in your context config. I'm not sure that is a legal config.
I had a similar issue where #Transactional didn't persist entity in the DB using EntityManager. To solve this problem we can commit the transaction manually.
entityManager.getTransaction().begin();
entityManager.persist(post);
entityManager.getTransaction().commit();
I'm creating a web application with Spring 3.1.0.RELEASE and JPA 2 with Hibernate Provider.
I'm doing the test with junit 4.10 , dbunit 2.4.8, unitils 3.3, hsqldb 2.2.8.
I try to test the service layer, a create operation. In my DAO i have this method:
#Override
#Transactional
public void createQuestion(Question question) {
logger.debug("createQuestion");
entityManager.persist(question);
logger.info("New question created [id] {}", question.getId());
}
My QuestionServiceTest test class :
#SpringApplicationContext("test-applicationContext.xml")
public class QuestionServiceTest extends UnitilsJUnit4 {
#SpringBeanByName
private QuestionService questionService;
#SpringBeanByName
private ThemeService themeService;
#Test
#DataSet("QuestionServiceTest.testCreateQuestion.xml")
#ExpectedDataSet("QuestionServiceTest.testCreateQuestion-result.xml")
public void testCreateQuestion() {
final Question newQuestion = new Question();
newQuestion.setCountryCode("FR");
newQuestion.setEmail("test#mytest.com");
newQuestion.setFirstName("FirstTest");
newQuestion.setLastName("LastTest");
newQuestion.setOriginalLang(LanguageEnum.FR);
newQuestion.setOriginalQuestion("This is the original question");
final Calendar calendar = Calendar.getInstance();
calendar.set(2012, 5, 12);
newQuestion.setCreationDate(calendar.getTime());
final Theme theme = themeService.findThemeById(new Integer(1));
newQuestion.setTheme(theme);
questionService.createQuestion(newQuestion);
}
}
I use the property hibernate.hbm2ddl.auto = create-drop for generate the schema, the question table is:
create table question (
id integer generated by default as identity (start with 1),
country_code varchar(10) not null,
creation_date timestamp not null,
email varchar(255) not null,
firstname varchar(100) not null,
lastname varchar(100) not null,
original_lang varchar(255) not null,
original_question clob not null,
theme_id integer not null,
primary key (id)
)
theme_id is a foreign key to table theme.
When i launch the test with ExpectedDataSet, the insert works but the test never finish.
The test block on :
DEBUG: org.dbunit.database.AbstractResultSetTable - Query: select
"ID", "COUNTRY_CODE", "CREATION_DATE", "EMAIL", "FIRSTNAME",
"LASTNAME", "ORIGINAL_LANG", "ORIGINAL_QUESTION", "THEME_ID" from
"PUBLIC"."QUESTION" order by "ID"
This is the last line on debug.
My unitils.properties is :
# Defaults and other keys with explanations can be found there: http://unitils.org/unitils-default.properties
database.driverClassName=org.hsqldb.jdbcDriver
database.url=jdbc:hsqldb:mem:testOpen
database.userName=sa
database.password=
database.dialect=hsqldb
# This schema is the initial schema when a new session is started in HSQLDB, don't change it or test won't works !
database.schemaNames=PUBLIC
dbUnit.datasetresolver.prefixWithPackageName=false
dbUnit.datasetresolver.pathPrefix=dataSets
My persistence.xml :
<persistence-unit name="OpenTestPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:testOpen" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
What should I do? I already try previous release of dbunit or unitils but it doesn't change anything. Expected Dataset is really cool feature.
Thanks.
I had the same issue and failed to solve it. Then I gave a try to
spring-test-dbunit
and this lib run smoothly.