Hibernate + MSSQL Erro

6 respostas
R

Estou fazendo aplicação com hibernate + struts + mssql. De inicio tenho somente uma tabela estou fazendo consulta e inserção. Fiz o teste no banco de dados MySQL e MSSQL.
OBS: No MySQL funcionou normalmente só q no MSSQL já não funcionou tão bem assim ele está instavel onde eu faço uma consulta normal nao da erro ai faço de novo a mesma consulta da erro ou seja bem instavel segue abaixo os meus arquivos de configurações, logs. Por favor se alguem souber agradeço.

hibernate.cfg.xml

<!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.SQLServerDialect
		</property>
		<property 
			name="hibernate.connection.driver_class">
			com.microsoft.jdbc.sqlserver.SQLServerDriver
		</property>
		<property 
			name="hibernate.connection.url">
			jdbc:microsoft:sqlserver://servidor:1433;DatabaseName=bancoDados
		</property>
		<property 
			name="hibernate.connection.username">
			usuario
		</property>
		<property 
			name="hibernate.connection.password">
			senha
		</property>		
		
		<!-- Condiguração do c3p0 -->
		
		<property name="hibernate.c3p0.max_size">10</property>
		<property name="hibernate.c3p0.min_size">2</property>
		<property name="hibernate.c3p0.timeout">5000</property>		
		<property name="hibernate.c3p0.max_statements">10</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>			

		<!-- Configurações de debug -->

		<property name="show_sql">true</property>
        <property name="use_outer_join">true</property>	
        <property name="hibernate.generate_statistics">true</property>
        <property name="hibernate.use_sql_comments">true</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>
		<!-- Drop and re-create the database schema on startup -->
		<!-- <property name="hbm2ddl.auto">create</property>-->
		
		
		<mapping resource="br/com/bull/bean/UserAdmin.hbm.xml"/>
		
			
	</session-factory>
</hibernate-configuration>

UserAdmin.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping 
	PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    

    <hibernate-mapping>
    	
    	<class name="br.com.bull.bean.UserAdminBean" table="USERADMIN">
    		<id name="id" column="idUserAdmin">
    			<generator class="identity"/>
    		</id>
    		
			<property name="nome" />
			<property name="re" />
    		<property name="createDT" type="calendar" />
    		<property name="senha" />
    	</class>
    	
    	
    	
    </hibernate-mapping>

Metodo que chama a consulta

public List listar(String coluna,String operador,String valor) throws HibernateException{
		
		//Session session = HibernateUtility.currentSession();
		List listAdministradores = null;
		
		try{
						HibernateUtility.beginTransaction();
						
			if(operador.equals("like")){
						Criteria criteriaLike = HibernateUtility.currentSession().createCriteria(UserAdminBean.class);
						criteriaLike
				.add(Restrictions.like(coluna,valor,MatchMode.ANYWHERE))
				.addOrder(Order.asc(coluna));
									
			listAdministradores = criteriaLike.list() ;
						}
						HibernateUtility.commitTransaction();
			System.err.println("7");
		}catch(HibernateException e){
			
			HibernateUtility.rollbackTransaction();
			
			System.err.println(e.toString());
			throw e;
		}finally{
			HibernateUtility.closeSession();
		}
		
	
		
		return  listAdministradores;
	}

LOGS de ERRO

[13/03/07 13:08:27:158 GMT-03:00] 6ed56040 SystemOut     O Hibernate: /* criteria query */ select this_.idUserAdmin as idUserAd1_0_0_, this_.nome as nome0_0_, this_.re as re0_0_, this_.createDT as createDT0_0_, this_.senha as senha0_0_ from USERADMIN this_ where this_.nome like ? order by this_.nome asc
[13/03/07 13:08:27:538 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  SQL Warning: 0, SQLState: 
[13/03/07 13:08:28:510 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to wflgcdi
[13/03/07 13:08:28:550 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  SQL Warning: 0, SQLState: 
[13/03/07 13:08:28:560 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Changed database context to 'wflgcdi'.
[13/03/07 13:08:28:560 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  SQL Warning: 0, SQLState: 
[13/03/07 13:08:28:570 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  [Microsoft][SQLServer 2000 Driver for JDBC]Language changed to us_english
[13/03/07 13:08:28:580 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  SQL Warning: 0, SQLState: 
[13/03/07 13:08:28:590 GMT-03:00] 6ed56040 JDBCException W org.hibernate.util.JDBCExceptionReporter  [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Changed language setting to us_english.
[13/03/07 13:08:36:812 GMT-03:00] 55aaa041 SystemOut     O Hibernate: /* criteria query */ select this_.idUserAdmin as idUserAd1_0_0_, this_.nome as nome0_0_, this_.re as re0_0_, this_.createDT as createDT0_0_, this_.senha as senha0_0_ from USERADMIN this_ where this_.nome like ? order by this_.nome asc
[13/03/07 13:08:36:902 GMT-03:00] 55aaa041 JDBCException W org.hibernate.util.JDBCExceptionReporter  SQL Error: 0, SQLState: 08007
[13/03/07 13:08:38:024 GMT-03:00] 55aaa041 JDBCException E org.hibernate.util.JDBCExceptionReporter  [Microsoft][SQLServer 2000 Driver for JDBC]Can't start a cloned connection while in manual transaction mode.
[13/03/07 13:08:38:044 GMT-03:00] 55aaa041 SystemErr     R org.hibernate.exception.JDBCConnectionException: could not execute query

6 Respostas

Eduardo_Bregaida

Eu to com esse erro, qdo era Derby funcionava mas agora c/ MYSQL...

(Mal nao criar um topico, é q ta dando pau aki no GUJ, e aproveitei q esse é de DB + Hibernate...)

13:34:20,730  INFO SchemaExport:154 - Running hbm2ddl schema export
13:34:20,730 DEBUG SchemaExport:170 - import file not found: /import.sql
13:34:20,730  INFO SchemaExport:179 - exporting generated schema to database
13:34:50,261  WARN BasicResourcePool:1222 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1a62c31 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
13:34:50,261 ERROR SchemaExport:202 - schema export unsuccessful
java.sql.SQLException: Connections could not be acquired from the underlying database!
	at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:104)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:236)
	at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94)
	at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
	at org.hibernate.tool.hbm2ddl.ManagedProviderConnectionHelper.prepare(ManagedProviderConnectionHelper.java:28)
	at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:180)
	at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:133)
	at br.com.fireant.confighibernate.GerarBanco.main(GerarBanco.java:22)
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
	at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970)
	at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232)
	... 6 more
hibernate.cgf.xml
<!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.url">
			jdbc:mysql://localhost/BD
		</property>
		<property name="hibernate.connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>

		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>

		<!-- usar C3P0 Pool de conexões-->
		<property name="hibernate.c3p0.min_size">1</property>
		<property name="hibernate.c3p0.max_size">5</property>
		<property name="hibernate.c3p0.maxIdleTime">200</property>
		<property name="hibernate.c3p0.timeout">180</property>
		<property name="hibernate.c3p0.idle_test_period">100</property>
		<property name="hibernate.c3p0.max-statements">50</property>


		<mapping class="br.com.fireant.acesso.Acesso"/>
		<mapping class="br.com.fireant.cadastro.Cadastro"/>

	</session-factory>
</hibernate-configuration>
H

Eu tive alguns problemas assim com o Hibernate e MSSQL… consegui resolver substituindo o Driver JDBC da M$ por um open source. http://jtds.sourceforge.net/

boa sorte

R

Galera encontrei o erro na pagina do hibernate http://www.hibernate.org/120.html

[b]
Hibernate doesn’t work with my MS SQL 2000 JDBC driver?
(Glen Stampoultzis)

If you’re using Hibernate with the Microsoft SQL Server 2000 JDBC driver chances are you’ll run into this problem:

java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]
Can’t start a cloned connection while in manual transaction mode.
Simply add SelectMethod=Cursor; to your connection string. There’s a MS knowledge base article with more information. The Microsoft SQL Server 2005 JDBC driver has been certified by JBoss Inc.

[/b]

e tbm na pagina da microsoft http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B313181

[b]
SYMPTOMS
While using the Microsoft SQL Server 2000 Driver for JDBC, you may experience the following exception:

java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Can’t start a cloned connection while in manual transaction mode.
Back to the top

CAUSE
This error occurs when you try to execute multiple statements against a SQL Server database with the JDBC driver while in manual transaction mode (AutoCommit=false) and while using the direct (SelectMethod=direct) mode. Direct mode is the default mode for the driver.
Back to the top

RESOLUTION
When you use manual transaction mode, you must set the SelectMethod property of the driver to Cursor, or make sure that you use only one active statement on each connection as specified in the “More Information” section of this article.
Back to the top

[/b]

import java.sql.*;
import java.io.*;


public class Repro{

	public static void main(String args[])
	{
		try {
			Connection con;
			Statement s1 = null;
			ResultSet r1 = null;
			Statement s2 = null;
			ResultSet r2 = null;
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); 
			con = DriverManager.getConnection(
				"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs;SelectMethod=Direct;User=User;Password=Password");
			//fix 1
				//"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs;[b]SelectMethod=Cursor[/b];User=User;Password=Password");
			con.setAutoCommit(false);
			
			try {
				s1 = con.createStatement();
				r1 = s1.executeQuery("SELECT * FROM authors");
				
				//fix 2
				//r1.close();
				//s1.close();

				s2 = con.createStatement();
				r2 = s2.executeQuery("SELECT * FROM publishers");
			}
			catch (SQLException ex)
			{
				System.out.println(ex);				
			}
		
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

Espero ter ajudado

heitor.rapcinski

Se não quiser ter todo esse trabalho, basta usar o JDBC jTDS!!!

R

na verdade é só acrescentar esse código na url de conexão SelectMethod=Cursor

obrigado pelo jTDS eu não conhecia ele é interessante

L

No hibernate.cfg então ficaria assim:

<property name="connection.url">
			jdbc:microsoft:sqlserver://10.10.140.123:1433;SelectMethod=Cursor
		</property>

??

Porque aqui não funcionou…

Criado 13 de março de 2007
Ultima resposta 16 de jul. de 2008
Respostas 6
Participantes 5