Spring Hibernate MySQL Test doesn't roll back - mysql

I have a problem with transactional tests using Spring 3.0.5, Hibernate 3 and MySQL 5.
In logs it seems there's everything OK and transaction rolls back, but I got record inserted into database.
My configuration is like this:
<bean id="hibernateDataSource" 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/blog" />
<property name="username" value="user" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="hibernateDataSource" />
<property name="schemaUpdate" value="true" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.autocommit">false</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>pl.jedenpies.blog.domain.Uzytkownik</value>
</list>
</property>
</bean>
<bean id="uzytkownikDao" class="pl.jedenpies.blog.db.hibernate.dao.HibernateUzytkownikDao">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
Test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:beans.xml"})
#TransactionConfiguration(defaultRollback = true)
public class UzytkownikDaoTest {
private UzytkownikDao uzytkownikDao;
#Test
#BeforeTransaction
public void test1Config() {
Assert.notNull(uzytkownikDao, "UzytkownikDao nie moze byc null");
}
#Test
#Transactional
#Rollback
public void test2Create() {
Uzytkownik u = new Uzytkownik();
u.setEmail("my4#uzytkownik.pl");
u.setHaslo("blablabla");
Assert.isTrue(!u.isIdUstawione());
u = uzytkownikDao.create(u);
Assert.notNull(u, "Uzytkownik nie moze byc null");
Assert.isTrue(u.isIdUstawione());
}
#Resource
public void setUzytkownikDao(UzytkownikDao uzytkownikDao) {
this.uzytkownikDao = uzytkownikDao;
}
}
Log:
DEBUG org.hibernate.event.def.AbstractSaveEventListener - executing identity-insert immediately
DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
DEBUG org.hibernate.jdbc.AbstractBatcher - insert into uzytkownicy (email, haslo) values (?, ?)
Hibernate: insert into uzytkownicy (email, haslo) values (?, ?)
DEBUG org.hibernate.id.IdentifierGeneratorFactory - Natively generated identity: 43
DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
DEBUG org.springframework.test.context.transaction.TransactionalTestExecutionListener - Method-level #Rollback(true) overrides default rollback [true] for test context [[TestContext#3dbbd23f testClass = UzytkownikDaoTest, locations = array<String>['classpath:beans.xml'], testInstance = pl.jedenpies.blog.dao.UzytkownikDaoTest#22a010ba, testMethod = test2Create#UzytkownikDaoTest, testException = [null]]]
DEBUG org.springframework.transaction.support.AbstractPlatformTransactionManager - Initiating transaction rollback
DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Rolling back Hibernate transaction on Session [org.hibernate.impl.SessionImpl#303bc1a1]
DEBUG org.hibernate.transaction.JDBCTransaction - rollback
DEBUG org.hibernate.transaction.JDBCTransaction - rolled back JDBC Connection
DEBUG org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Closing Hibernate Session [org.hibernate.impl.SessionImpl#303bc1a1] after transaction
DEBUG org.springframework.orm.hibernate3.SessionFactoryUtils - Closing Hibernate Session
Yes, I googled a lot this problem but didn't really find a solution. I have no idea what's wrong.
Any suggestions?

Do you are using InnoDB engine? MyISAM is the default engine form MySQL 5.x prior to 5.5 and does not support transactions - Wikipedia - MyISAM

Remove the following Hibernate property, it conflicts with Spring transaction management:
<prop key="hibernate.current_session_context_class">thread</prop>

Related

How to configure MySQL JTA resource in Spring, JPA and Hibernate for Glassfish v3?

My application is able to perform the read operations but unable to write to the database. How should I configure the JTA transaction manager? I'm using the following: Glassfish 3.1.2.2, Hibernate 4.2.21, Spring 4.2.5, MySQL 5.6 and JDK 1.6. I've tried the following configuration:
persistence.xml
<persistence-unit name="appPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<properties>
<!--<property name="hibernate.transaction.jta.platform"-->
<!--value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>-->
<!--<property name="hibernate.transaction.factory_class" value="org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"/>-->
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
</properties>
</persistence-unit>
web.xml
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/appPersistenceUnit</persistence-unit-ref-name>
<persistence-unit-name>appPersistenceUnit</persistence-unit-name>
</persistence-unit-ref>
applicationContext.xml
<jee:jndi-lookup id="entityManagerFactory"
jndi-name="persistence/appPersistenceUnit"/>
<tx:jta-transaction-manager/>
<tx:annotation-driven/>
MyDAOImpl.java
#PersistenceContext(type = PersistenceContextType.EXTENDED, name = "appPersistenceUnit")
protected EntityManager entityManager;
#Override
public int save(final MyEntity myEntity) {
try {
entityManager.merge(myEntity);
}
catch (Exception e) {
LOGGER.error("Error while saving MyEntity", e);
}
return 1; // id of the created element.
}
On trying to save the entity, I get the following error:
Cannot join transaction: do not override hibernate.transaction.factory_class
Please guide me. What am I doing wrong?

hibernate closing connections or not?

My code is below. Possibly I am using it many times in similar manner, i.e in simple words, I am managing the session and transaction this way:
List<Login> users= null;
try{
session=HibernateUtil.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
users=session.createQuery("from Login").list();
tx.commit();
}catch(Exception e){System.out.println("commit exception:"+e);
try {tx.rollback();} catch (Exception ex) {System.out.println("rollback exception:"+ex);}
}finally{if(session!=null && session.isOpen()){session.close();}}
return users;
Now, when I first run the database service(using MySQL) and check from command prompt using this query ...
show status like 'Conn%';
... the result is:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 2 |
+---------------+-------+
When I start my application and use it. After opening few pages and querying the same thing. I am getting the connections as 6, I have even seen above 20.
Now I would like to know that hibernate is closing the connections or not?
I am handling all the transactions that way, I cross checked and dint see any code block without closing the session.
Hibernate.cfg.xml
<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/shareapp
</property>
<property name="connection.username">pluto</property>
<property name="connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</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>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
hibernateutil class
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Login.class);
config.addAnnotatedClass(FilesInfo.class);
config.addAnnotatedClass(FilesShare.class);
config.configure("hibernate.cfg.xml");
// new SchemaExport(config).create(true,true);
sessionFactory = config.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Thanks!
The "Connections" status variable just refers to the
The number of connection attempts (successful or not) to the MySQL server,
and not the number of active connections.
Here is the link: http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Connections
To get the number of open connections, check the 'Threads_connected' variable, documented at
http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Threads_connected

Having connection issue Hibernate 3.0 with MySQL

I am getting this error. I have my hibernate connections and MVC all setup correct I believe.
I heard MySQL drivers have an issue for database connection.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/AdministrativeApplication] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] with root cause
java.sql.SQLException: Unknown database 'testDB'
My hibernate configuration file
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Load Hibernate related configuration -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="myroot"/>
<property name="password" value="*****"/>
<!-- connection pooling details -->
<property name="initialSize" value="1"/>
<property name="maxActive" value="5"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<!-- Declare a transaction manager-->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<!-- all the annotation entity classes -->
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
Please let me know what
I could do to resolve this error.
I further added a new java file to test
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "******";
String url = "jdbc:mysql://localhost:3306/testDB";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace(System.out);
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
I get this error . Also I started the MySQL console with this command.
"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
I get this error
java.sql.SQLException: Unknown database 'testdb'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:798)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3700)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1203)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2572)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:15)
Cannot connect to database server
Can some please help resolve this.
i ran netstats no luck. I do not see at what port MySQL is listening at.
Thanks again .
Dhiren
I am getting this error.
This means you did something wrong.
I have my hibernate connections and MVC all setup correct I believe.
See my previous comment - you did not do everything correctly.
I heard MySQL drivers have an issue for database connection.
Nope - MySQL drivers work fine if you set them up properly. You're doing something wrong, and you'll make progress faster if you take that attitude.
Before you run Java, start up the MySQL client, log into MySQL. If you can't, Java won't be able to, either. See if the daemon is up and running.
See if you have that database available. If not, create it.
If it is created, make sure that you have the tables you need and the user you're logging in as has appropriate permissions.
You could create a database named "testDB" in your MySQL instance.

Jackson Jaxb Json with Apache CXf

I am using Jackson Jaxb JSON in my REST project with Apache CXF
JacksonJaxb version . 1.7.0
Apache CXF 2.3.1
I am using following code to return from my method.
#GET
#Consumes({ "application/json", "application/xml", "text/xml" })
#Path("/job/autosuggest")
#Override
public Response getSuggestions(String searchField, Integer resPerPage, String typeCont)
{
List<String> respo = new ArrayList<String>();
respo.add("Atish");
respo.add("Narlawar");
respo.add("India");
return Response.ok(respo).build();
}
Now issue is coming when I compile and run the code on jetty, I get stuck with
DEBUG o.s.b.f.s.DefaultListableBeanFactory [] Finished creating instance of bean 'org.apache.cxf.phase.PhaseManager'
org.codehaus.jackson.map.JsonMappingException: Incompatible types: declared root type ([simple type, class javax.ws.rs.core.Response]) vs java.util.ArrayList
This is not particular to array or wrapper, but any object If I pass rather than String in Response.ok(object) fails to parse.
My configuration is
<util:map id="jsonNamespaceMap" map-class="java.util.Hashtable">
<entry key="http://services.institute.com" value=""/>
<entry key="http://cxf.apache.org/bindings/xformat" value="cxf"/>
</util:map>
<bean id="jsonInputFactory" class="org.codehaus.jettison.mapped.MappedXMLInputFactory">
<constructor-arg ref="jsonNamespaceMap"/>
</bean>
<bean id="jsonOutputFactory" class="org.codehaus.jettison.mapped.MappedXMLOutputFactory">
<constructor-arg ref="jsonNamespaceMap"/>
</bean>
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider"/>
<jaxrs:server id="jobsearch" address="/">
<jaxrs:serviceBeans>
<ref bean="jobSearchService" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings>
<entry key="text" value="text/xml"/>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
</jaxrs:extensionMappings>
<jaxrs:languageMappings/>
<jaxrs:properties>
<entry key="javax.xml.stream.XMLInputFactory">
<ref bean="jsonInputFactory"/>
</entry>
<entry key="javax.xml.stream.XMLOutputFactory">
<ref bean="jsonOutputFactory"/>
</entry>
</jaxrs:properties>
<jaxrs:providers>
<ref bean="jsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>
I am not sure how to proceed on this issue. I already lost 1/2 day to get some workaround. Any help will be appreciated.
Thanks in advance !
At last I got the answer.
The issue is with the version itself.
JacksonJaxb has reported bug in 1.7.0.
I updated the version to higher...in my case it is 1.8.5 and it got fixed.
Hope this helps.
Thanks
Atish

Fluent NHibernate Mapping Exception On Compiling Mapping Document

I have an NHibernate configuration file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="MyProject">
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string_name">MyProject</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
</session-factory>
</hibernate-configuration>
When creating the Configuration object:
Configuration cfg = new Configuration();
cfg.AddFile(nhibernateConfigurationFile);
I'm getting the following errors when trying to run a persistence test:
System.InvalidOperationException: Could not find the dialect in the configuration
NHibernate.MappingException: Could not compile the mapping document: C:\PathToProject\bin\Debug\NHibernateMyProject.config
Anyone know why it is having trouble reading the nhibernate config file? From what I am able to see, the dialect is definitely in the config....
You should use this dialect: NHibernate.Dialect.MsSql2000Dialect
Try to define the assembly which contains the mapping files:
<mapping assembly="yourAssembly"/>
For the configuration file:
new Configuration().Configure( yourfile.cfg.xml );