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 );
Related
sorry for my bad english, (Im french :-D).
I want work with TomEE for JPA, but my configuration is bad i think.
I receive a exception when i try to connecte to my database (Mysql).
persistence.xml
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>elevage</jta-data-source>
<non-jta-data-source>elevageUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
tomee.xml
<Resource id="elevage" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
DefaultAutoCommit false
</Resource>
<Resource id="elevageUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>
Exception
AVERTISSEMENT: Unexpected exception from beforeCompletion; transaction will roll back
<openjpa-2.4.1-r422266:1730418 fatal general error> org.apache.openjpa.persistence.PersistenceException: user lacks privilege or object not found: OPENJPA_SEQUENCE_TABLE {SELECT SEQUENCE_VALUE FROM OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=-5501, state=42501]
Request is a "SELECT" and i want take all data in my database. I have see documentation but the problem persiste.
Thank all for your answer !
(if you need more file, tell me :-) )
After a long time tearing my hair, I found a solution, if it can save time, here it is:
2 Configurations!
In development:
tomee.xml is not used, it is necessary to configure openejb.xml whose path is specified in the eclipse console, attention, the access is by hidden file
Path for my machine (Linux):
/home/user/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/conf/openejb.xml
At the bottom of the file, you have section "Resource", the configuration is identical to tomee.xml (you can find documentation at this adress : documentation for configuration tomee.xml
In production:
we forget openejb.xml, a configuration is identical but in tomee.xml
to finish, here is my configuration:
persistence.xml
<persistence version="2.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_2_0.xsd">
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>MyDataBase</jta-data-source>
<non-jta-data-source>MyDataBaseUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<!-- <class>com.test.ejb.BeanUser</class>-->
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
openejb.xml (in development) and tomee.xml (in production)
<Resource id="MyDataBase" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
</Resource>
<Resource id="MyDataBaseUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>
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?
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.
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
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>