I'm using SQL Server 2008 with Hibernate 3.0 at data access layer of my application. The problem is that I'm unable to read from database.
Here is my Hibernate config;
<property name="connection.driver_class"> com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost;databaseName=test;integratedSecurity=true;</property>
<property name="connection.username">not required</property>
<property name="connection.password"></property>
<property name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="user.hbm.xml"/>
Here is user.hbm.xml
<class name="ammar.User" table="user" schema="dbo" catalog="test">
<id name="userId" type="int" column="userId" >
<generator class="assigned"/>
</id>
<property name="userName">
<column name="userName" />
</property>
</class>
And here is code I'm using to get data from database.
SessionFactory sF = new Configuration().configure().buildSessionFactory();
Session session = sF.openSession();
User user = (User) session.get(User.class, 1);
if(user!=null)
System.out.println(user.getUserName());
else
System.out.println("Not Found");
SQLGrammarException as well as SQLServerException occurs when I run this.
Urgent reply is needed.
Solved. Actually 'user' a is reserved word in SQL Server 2008. Anyhow, Thanks to #ManuPK.
Related
I use hibernate to save data into MySQL, but I got ultraedit.
enter image description here
My code is below:
#Test
public void testA(){
Employee emp = new Employee();
emp.setEmpName("邓海");
emp.setWorkDate(new Date());
Configuration conf = new Configuration();
conf.configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction();
session.save(emp);
ts.commit();
session.close();
sf.close();
}
And my .hbm.xml is below:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ypd.a.entity">
<class name="Employee" table="t_employee">
<id name="empId" column="id">
<generator class="native"/>
</id>
<property name="empName" column="emp_name"></property>
<property name="workDate" column="workDate"></property>
</class>
</hibernate-mapping>
My hibernate.xml is :
hibernate-configuration >
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="javax.persistence.validation.mode">none</property>
<mapping resource="Employee.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Edit
enter image description here
If there is some settings I don't know? please show me the correct setting.
Try this in your sessionFactory:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8</property>
You should appoint out the charset when you communication with the server.
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
}
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.
my hibernate.cfg.xml is this :
<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/****</property>
<property name="hibernate.connection.username">***</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactor y</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">create</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<mapping class="entities.MisurazioneOraria"/>
<mapping class=....
....>
<listener type="post-insert" class="MisurazioneOrariaInsertListener"/>
</session-factory>
</hibernate-configuration>
i try to do query from this line code that is the listener :
ArrayList<MisurazioneOraria> mis = (ArrayList<MisurazioneOraria>) session.createQuery("from (misurazione_oraria) where sensore_idsensore = :idsensore").setParameter("idsensore", m.getSensore().getIdSensore()).list();
and the error is that :
mag 27, 2012 6:30:33 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
Grave: Could not synchronize database state with session
org.hibernate.QueryException: in expected: misurazione_oraria [from (misurazione_oraria) where sensore_idsensore = :idsensore]
my mysql version is 5.5.23. thanks for the help.
Your entity class is named MisurazioneOraria, not misurazione_oraria. HQL uses entities and fields/properties. It doesn't use table and column names.
Read the HQL documentation.
Moreover, Query.list() returns a List, and not necessarily an ArrayList. You shouldn't cast the result of the query to ArrayList.
change it to
List<MisurazioneOraria> mis = session.createQuery("from MisurazioneOraria where idSensore = :idsensore").setParameter("idsensore", m.getSensore().getIdSensore()).list();