I'm integrate spring with hibernate , I'm using dropwizard configaration files as : persistence file have the configuration files are in resources folder no issue with loading xml files. There is issue with found table .
persistence.xml file as :
<persistence-unit name="bfm" transaction-type="RESOURCE_LOCAL" >
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.bcits.parkingmanagement.model.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/anuj" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</persistence-unit>
</persistence>
In spring application config xml as : there I show only hibernate configuration
<context:annotation-config />
<context:component-scan base-package="com.bcits.parkingmanagement.model" />
<jdbc:embedded-database id="dataSource" type="HSQL" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:spring/persistence.xml" />
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
Table User missing
javax.persistence.PersistenceException: [PersistenceUnit: bfm] Unable to build EntityManagerFactory
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 18 more
Caused by: org.hibernate.HibernateException: Missing table: user
Please anyone help me how can I resolve this error. I want to configuration of spring with hibernate.I thing it is connect to database but can't found table. Table name and colume name exactly same. Database name also correct and no issue with username and password of database .
User model is: Here User is model name and user is table which have two column one is user_id and user_name. Issue is that i had used user instead of User in query. Because User is model name and user is table name .Correct model is given below
#NamedQueries({
#NamedQuery( name="getUserName" , query="select name from User")
})
#Entity
#Table( name ="user")
public class User {
#Id
#Column( name="user_id")
private int id;
#Column( name="user_name")
private String name;
//getter setter
}
Related
I am trying to build a simple application using Hibernate JPA with MySQL but I keep getting a "Missing table" error whenever I try to deploy it to Wildfly.
My persistent class looks like this:
package com.example;
#Entity #Table
public class FooBar {
//...
}
Here is my 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="ExampleJPA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.example.FooBar</class>
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydatabase" />
<property name="javax.persistence.jdbc.user" value="(my user)" />
<property name="javax.persistence.jdbc.password" value="(my password)" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<!-- Hibernate properties -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<!-- Configuring Connection Pool -->
<property name="hibernate.c3p0.min_size" value="5" />
<property name="hibernate.c3p0.max_size" value="20" />
<property name="hibernate.c3p0.timeout" value="500" />
<property name="hibernate.c3p0.max_statements" value="50" />
<property name="hibernate.c3p0.idle_test_period" value="2000" />
</properties>
</persistence-unit>
</persistence>
And this is the message I get when deploying to a Wildfly 8 server:
org.jboss.msc.service.StartException in service jboss.persistenceunit.\"ExampleJPA.war#ExampleJPA\": org.hibernate.HibernateException: Missing table: FooBar
Caused by: org.hibernate.HibernateException: Missing table: FooBar
I do have a table called FooBar in the database. I can access it directly with JDBC using the same url, user and password defined in the persistence.xml. What is wrong with my JPA setup?
Your table doesn't exist in the schema, so the hibernate.hbm2ddl.auto value of "validate" fails. Either create the table or change the hibernate.hbm2ddl.auto value to "create" or "update".
I have a test like the following
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:META-INF/spring/testDataSpringContext.xml" })
#Transactional
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
public class AgenceDAOTest {
#Autowired
private AgenceDAO mAgenceDAO;
#Test
#DatabaseSetup(value = "/META-INF/db-test/sampleData.xml", type = DatabaseOperation.REFRESH)
public void listAgences() {
List<AgenceVO> vListeAgences = mAgenceDAO.getAgences();
Assert.notNull(vListeAgences);
Assert.notEmpty(vListeAgences);
List<AgenceVO> vListeAgencesTrouvees = ListUtils.select(vListeAgences, new Predicate<AgenceVO>() {
public boolean evaluate(AgenceVO pAgenceVO) {
return pAgenceVO.getLibelle().startsWith("TEST_");
}
});
Assert.notNull(vListeAgencesTrouvees);
Assert.notEmpty(vListeAgencesTrouvees);
Assert.isTrue(vListeAgencesTrouvees.size() == 1);
}
}
Everything seems ok because in the log I see the following:
[TransactionalTestExecutionListener: startNewTransaction];Began transaction (1): transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager#39d325]; rollback [true]
[DbUnitTestExecutionListener: setupOrTeardown];Executing Setup of #DatabaseTest using REFRESH on /META-INF/db-test/sampleData.xml
[AbstractTableMetaData: getDataTypeFactory];Potential problem found: The configured data type factory 'class org.dbunit.dataset.datatype.DefaultDataTypeFactory' might cause problems with the current database 'Oracle' (e.g. some datatypes may not be supported properly). In rare cases you might see this message because the list of supported database products is incomplete (list=[derby]). If so please request a java-class update via the forums.If you are using your own IDataTypeFactory extending DefaultDataTypeFactory, ensure that you override getValidDbProducts() to specify the supported database products.
[SQL: logStatement];select this_.AGC_ID as AGC1_0_0_, this_.AGC_CP as AGC2_0_0_, this_.AGC_ADR1 as AGC3_0_0_, this_.AGC_COMMUNE as AGC4_0_0_, this_.AGC_ADR2 as AGC5_0_0_, this_.AGC_LIBELLE as AGC6_0_0_, this_.AGC_MAIL as AGC7_0_0_, this_.AGC_NOM as AGC8_0_0_, this_.AGC_TEL as AGC9_0_0_ from FTN_AGENCE_AGC this_
[DbUnitTestExecutionListener: verifyExpected];Skipping #DatabaseTest expectation due to test exception class java.lang.IllegalArgumentException
[TransactionalTestExecutionListener: endTransaction];Rolled back transaction after test execution for test context [[TestContext#cdd54e testClass = AgenceDAOTest, locations = array<String>['classpath:META-INF/spring/testDataSpringContext.xml'], testInstance = com.edf.ftn.data.admin.AgenceDAOTest#16f2067, testMethod = listAgences#AgenceDAOTest, testException = java.lang.IllegalArgumentException: [Assertion failed] - this collection must not be empty: it must contain at least 1 element]]
The dbunit dataset is loaded after the transaction is created, so dataset data should be visible in select, but it is not visible. When the select is executed records in the dataset are not retrieved.
To verify if the dataset is being loaded I've tried to insert a duplicate key and an exception is launched, so I supose that de dataset is loaded correctly.
The datasource and transactionmanager configuration is:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#${ip}:${port}:${schema}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
The DAO is not configured as transactional, because in the application it isn't. But I have also tried to make it transactional, and the result is the same.
I do not understand why in this line:
List<AgenceVO> vListeAgences = mAgenceDAO.getAgences();
The dataset is not visible.
Solution found
I fixed the problem by using TransactionAwareDataSourceProxy
Finally I've got the following configuration for datasource:
<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#${ip}:${port}:${schema}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg ref="dbcpDataSource" />
</bean>
<bean id="futunoaTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
HINT : My hosting tomcat system provides only 20 db connections
My working project in localhsot
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
This worked good in localhost, but in production it run for a while and Exception : "user has allready max no of connection".
After many google
I used c3p0
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
This worked in localhost, but same problem in production server
Hint: I think some config in c3p0 can solve this. Please help me with you suggestion (My hosting provides only 20 connections)
Also i tried tomcat
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSourceFactory">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="20"/>
</bean>
The above tomcat code is wrong and will not work - because wrong property (I know that). How to set this for my production use(only 20 connections)
If you know how to use tomcat pool please help us.
I also used bonecp
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="idleConnectionTestPeriod" value="60"/>
<property name="idleMaxAge" value="240"/>
<property name="maxConnectionsPerPartition" value="10"/>
<property name="minConnectionsPerPartition" value="5"/>
<property name="partitionCount" value="1"/>
<property name="acquireIncrement" value="5"/>
<property name="statementsCacheSize" value="1000"/>
<property name="releaseHelperThreads" value="3"/>
</bean>
This worked in localhost but same problem in production "user has to many connections".
I also tried apache-dbcp
As per tomcat 7 documentation - dbcp is no longer and tomcat will be bundled with pool. Even though i used dbcp and i cannot run my program. (I added only one jar and error was some class not found during project run)
As per my own idea :
I think above mentioned settings will be problem. Please help me with your suggestions. I'm not using hibernate up to now because of heavy weight. If hibernate can solve this problem please let us know.
EDITED
Currently I'm using this code. Is this code correct to my use(20 connection)
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}" p:password="${jdbc.password}"
p:acquireIncrement="1"
p:checkoutTimeout="1"
p:idleConnectionTestPeriod="5"
p:maxIdleTime="5"
p:maxIdleTimeExcessConnections="1"
p:maxPoolSize="20" p:maxStatements="0" p:maxStatementsPerConnection="0"
p:minPoolSize="1"
p:numHelperThreads="100"
p:overrideDefaultUser="${jdbc.username}" p:overrideDefaultPassword="${jdbc.password}"
p:propertyCycle="3"
p:testConnectionOnCheckin="true"
p:unreturnedConnectionTimeout="5" />
DAO code :
#Repository
public class TutorialsDAOImpl implements TutorialsDAO {
//---
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
#Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
//---
#Override
public List<TutorialsCategory_vo> getTutorialsCategory() {
sql = "SELECT * FROM `tutorials_category` ORDER BY `slug` ASC;";
List<TutorialsCategory_vo> vo = null;
try {
vo = this.jdbcTemplate.query(sql, new Object[]{}, tutorialsCategory_mapper);
} catch (Exception e) {
log.log(Level.SEVERE, null, e);
}
return vo;
}
These are the codes i'm using. If there is any error/corrections pls correct me.
Edited (for Arun P Johny 's question)
My current project url.
I updated my current code above.
This is my final c3p0 settings:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}" p:password="${jdbc.password}"
p:acquireIncrement="1"
p:checkoutTimeout="3000"
p:idleConnectionTestPeriod="5"
p:maxIdleTime="3"
p:maxIdleTimeExcessConnections="1"
p:maxPoolSize="20" p:maxStatements="20000" p:maxStatementsPerConnection="1000"
p:minPoolSize="1"
p:numHelperThreads="1000"
p:overrideDefaultUser="${jdbc.username}" p:overrideDefaultPassword="${jdbc.password}"
p:propertyCycle="3"
p:statementCacheNumDeferredCloseThreads="1"
p:testConnectionOnCheckin="true"
p:unreturnedConnectionTimeout="7" />
This works fine, but taking more time(1 or 2 secounds - not more than 3 secounds).
I also checked this code by shutting down mysql. My program waited up to, i start mysql. This is good. This code waits for all db connections to complete and out put correctly.
Can we make this settings even faster? Hint: my server provides only 20 connections.
If you provide a correct answer i'll make it as right answer, after checking.
I have the following configuration :
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<!-- XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
It creates a json, but the root name is not what i want
#XStreamAlias("house")
#JsonAutoDetect
#JsonRootName(value = "house")
public class TableHouse {
private Long value;
.....
}
For the xml it works fine, however for the json it does not pick up the #JsonRootName.. and outputs json with class name as root...
Any ideas?
You have to enable root-level wrapping. See How do I rename the root key of a JSON with Java Jackson? to have an idea on how to use JsonRootName properly.
I am doing unit testing and I expect that all data committed to the MySQL database will be rolled back... but this isn't the case. The data is being committed, even though my log was showing that the rollback was happening. I've been wrestling with this for a couple days so my setup has changed quite a bit, here's my current setup.
LoginDAOTest.java:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:web/WEB-INF/applicationContext-test.xml", "file:web/WEB-INF/dispatcher-servlet-test.xml"})
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class UserServiceTest {
private UserService userService;
#Test
public void should_return_true_when_user_is_logged_in ()
throws Exception
{
String[] usernames = {"a","b","c","d"};
for (String username : usernames)
{
userService.logUserIn(username);
assertThat(userService.isUserLoggedIn(username), is(equalTo(true)));
}
}
ApplicationContext-Text.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/******"/>
<property name="username" value="*****"/>
<property name="password" value="*****"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="userService" class="Service.UserService">
<property name="userDAO" ref="userDAO"/>
</bean>
<bean id="userDAO" class="DAO.UserDAO">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>/himapping/User.hbm.xml</value>
<value>/himapping/setup.hbm.xml</value>
<value>/himapping/UserHistory.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
I have been reading about the issue, and I've already checked to ensure that the MySQL database tables are setup to use InnoDB. Also I have been able to successfully implement rolling back of transactions outside of my testing suite. So this must be some sort of incorrect setup on my part.
Any help would be greatly appreciated :)
The problem turned out to be that the connection was auto-committing BEFORE the transaction could be rolled back. I had to change my dataSource bean to include a defaultAutoCommit property:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="Ecosim07"/>
<property name="defaultAutoCommit" value="false" />
</bean>
For me defaultAutoCommit and #Transactional didn't help. I had to change db type to InnoDB
Another way to fix your problem:
Instead of using:
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
, which creates a MyISAM table by default, hence not supporting transactions
Try using
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
, which creates InnoDB tables, and thus supports transactions.
This must be used
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#TestExecutionListeners({ TransactionalTestExecutionListener.class })
#Transactional
TransactionalTestExecutionListener contains isRollback() which rollbacks the
transaction after the test method.
I hope I am right and that this is a simple one. You are missing the #Transactional annotation on your test class. This means that the test method itself isn't run in a transaction and thus there is nothing to roll back. Hope this helps.