-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: Hibernate creates wrong Statement
PostPosted: Thu Aug 13, 2009 5:22 am 
Newbie

Joined: Thu Aug 13, 2009 4:52 am
Posts: 12
i have 2 databases for testing: 1x MySQL, 1x MS SQL Server 2008

both DBs have the table called "user"

in MySQL, "select * from user" works
in MS SQL, it has to be "select * from [user]"

i though that Hibernate can do it from itself... but when i want to get the users on the MS SQL Server, Hibernate still creates this statement:

Code:
Hibernate: select user0_.uid as uid1_, user0_.BEGROUP as BEGROUP1_,  BLAH BLAH BLAH  from .user user0_

...causing an SQL-Error

my java-code has to work with both DBs ... MySQL AND MS SQL ... (otherwise hibernate makes no sense for our project)

can anyone help me out?

greetings
lenaz


edit:
here's my hibernate.cfg.xml:

Code:
<hibernate-configuration>

   <session-factory>
      <property name="dialect">
         org.hibernate.dialect.SQLServerDialect
      </property>
      <property name="connection.url">
         jdbc:sqlserver://192.xxx.xxx.xxx:1433;databaseName=adb;
      </property>
      <property name="connection.username">****</property>
      <property name="connection.password">****</property>
      <property name="connection.driver_class">
         com.microsoft.sqlserver.jdbc.SQLServerDriver
      </property>
      
      
      <property name="hibernate.c3p0.min_size">0</property>
      <property name="hibernate.c3p0.max_size">30</property>
      <property name="hibernate.c3p0.timeout">600</property>
      <property name="hibernate.c3p0.max_statements">0</property>
      <property name="hibernate.c3p0.acquire_increment">1</property>
      <property name="hibernate.c3p0.idle_test_period">60</property>
      <property name="hibernate.c3p0.preferredTestQuery">SELECT 1;</property>
      <property name="connection.autocommit">true</property>
      <property name="connection.zeroDateTimeBehavior">convertToNull</property>
      <property name="connection.jdbcCompliantTruncation">false</property>
      <property name="connection.autoReconnect">true</property>
      
      <property name="hibernate.show_sql">true</property>
      
      <mapping resource="hibernate/mappings/Angebot.hbm.xml" />
      <mapping resource="hibernate/mappings/User.hbm.xml" />

   </session-factory>

</hibernate-configuration>



Top
 Profile  
 
 Post subject: Re: Hibernate creates wrong Statement
PostPosted: Thu Aug 13, 2009 7:54 am 
Expert
Expert

Joined: Tue May 13, 2008 3:42 pm
Posts: 919
Location: Toronto & Ajax Ontario www.hibernatemadeeasy.com
So, is the problem the fact that 'user' is a reserved word? Do you not have to treat it slightly differently in an MS environment due to this fact? Single quotes maybe?

-Cameron McKenzie

_________________
Cameron McKenzie - Author of "Hibernate Made Easy" and "What is WebSphere?"
http://www.TheBookOnHibernate.com Check out my 'easy to follow' Hibernate & JPA Tutorials


Top
 Profile  
 
 Post subject: Re: Hibernate creates wrong Statement
PostPosted: Thu Aug 13, 2009 8:05 am 
Newbie

Joined: Thu Aug 13, 2009 4:52 am
Posts: 12
Cameron McKenzie wrote:
So, is the problem the fact that 'user' is a reserved word? Do you not have to treat it slightly differently in an MS environment due to this fact? Single quotes maybe?

-Cameron McKenzie


yes, in MS Environment, 'user' is a reserved word. so it has to be treated this way [user]

i found a solution (but i got in a dilemma now ^^)


i wrote this class:
Code:
package hibernate;

import org.hibernate.cfg.DefaultNamingStrategy;
import org.hibernate.dialect.Dialect;

public class MaskingNamingStrategy extends DefaultNamingStrategy {
   
   //MySQL: `user` , MSSQL: [user]   
   private static Dialect _dialect;
   
   public MaskingNamingStrategy(){
      
      super();
      String d = HibernateSessionFactory.getConfiguration().getProperty("dialect");//"org.hibernate.dialect.MySQL5InnoDBDialect";
      if(d.equals("org.hibernate.dialect.MySQL5InnoDBDialect")){
         _dialect = new org.hibernate.dialect.MySQL5InnoDBDialect();
      }
      if(d.equals("org.hibernate.dialect.SQLServerDialect")){
         _dialect = new org.hibernate.dialect.SQLServerDialect();
      }
      System.out.println("MaskingNamingStrategy._dialect: "+d);
   }
   
   
   @Override
   public String classToTableName(String className)
   {

      System.out.println("Adding quotes to table from class "+className);
      return addQuotes(super.classToTableName(className));
   }
   
   @Override
   public String tableName(String tableName)
   {
      System.out.println("Adding quotes to table "+tableName);
      return addQuotes(super.tableName(tableName));
   }
   
   @Override
   public String columnName(String columnName)
   {
      System.out.println("Adding quotes to column "+columnName);
      return addQuotes(super.columnName(columnName));
   }

   /**
    * Adds opening and closing quotes as provided by the current dialect.
    *
    * @param input
    *          the input to quote
    * @return the qouted input
    */
   private static String addQuotes(String input)
   {
      return new StringBuffer().append(_dialect.openQuote())
                         .append(input)
                         .append(_dialect.closeQuote()).toString();
   }
      
}



as you can see, i am getting the used Dialect from the configuration - variable in my HibernateSessionFactory
BUT
i have to set the NamingStrategy at a time where the configuration is still NULL (unconfigured) ... argh


Top
 Profile  
 
 Post subject: Re: Hibernate creates wrong Statement
PostPosted: Thu Aug 13, 2009 8:33 am 
Newbie

Joined: Thu Aug 13, 2009 4:52 am
Posts: 12
ok, i solved it ... getting the dialect is maybe not the finest way, but it works

MaskingNamingStrategy.java:

Code:
package hibernate;

import org.hibernate.cfg.DefaultNamingStrategy;
import org.hibernate.dialect.Dialect;

public class MaskingNamingStrategy extends DefaultNamingStrategy {
   
   //MySQL: `user` , MSSQL: [user]   
   private static Dialect _dialect;
   
   public MaskingNamingStrategy(String configuredDialect){
      
      super();
      try {
         Class c = Class.forName(configuredDialect);
         _dialect = (Dialect) c.newInstance();
         
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      System.out.println("MaskingNamingStrategy._dialect: "+configuredDialect +"    --> "+_dialect.openQuote() +"tblName"+_dialect.closeQuote());
   }
   
   
   @Override
   public String classToTableName(String className)
   {
     //System.out.println("Adding quotes to table from class "+className);
      return addQuotes(super.classToTableName(className));
   }
   
   @Override
   public String tableName(String tableName)
   {
      //System.out.println("Adding quotes to table "+tableName);
      return addQuotes(super.tableName(tableName));
   }
   
   @Override
   public String columnName(String columnName)
   {
      //System.out.println("Adding quotes to column "+columnName);
      return addQuotes(super.columnName(columnName));
   }

   /**
    * Adds opening and closing quotes as provided by the current dialect.
    *
    * @param input
    *          the input to quote
    * @return the qouted input
    */
   private static String addQuotes(String input)
   {
      return new StringBuffer().append(_dialect.openQuote())
                         .append(input)
                         .append(_dialect.closeQuote()).toString();
   }
      
}




HibernateSessionFactory.java:

Code:
package hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import hibernate.MaskingNamingStrategy;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
   private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();   
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

   static {
       try {
          configuration.configure(configFile);
          MaskingNamingStrategy myNamingStrategy = new MaskingNamingStrategy(configuration.getProperty("dialect"));
          
          configuration = new Configuration();
         configuration.setNamingStrategy(myNamingStrategy);
         configuration.configure(configFile);
         
         sessionFactory = configuration.buildSessionFactory();
      } catch (Exception e) {
         System.err
               .println("%%%% Error Creating SessionFactory %%%%");
         e.printStackTrace();
      }
    }
    private HibernateSessionFactory() {
    }
   
   /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {System.out.println("HibernateSessionFactory for fsales DB");
        Session session = (Session) threadLocal.get();

      if (session == null || !session.isOpen()) {
         if (sessionFactory == null) {
            rebuildSessionFactory();
         }
         session = (sessionFactory != null) ? sessionFactory.openSession()
               : null;
         threadLocal.set(session);
      }

        return session;
    }

   /**
     *  Rebuild hibernate session factory
     *
     */
   public static void rebuildSessionFactory() {
      try {
         configuration.configure(configFile);
          MaskingNamingStrategy myNamingStrategy = new MaskingNamingStrategy(configuration.getProperty("dialect"));
          
          configuration = new Configuration();
         configuration.setNamingStrategy(myNamingStrategy);
         configuration.configure(configFile);
         
         sessionFactory = configuration.buildSessionFactory();
      } catch (Exception e) {
         System.err
               .println("%%%% Error Creating SessionFactory %%%%");
         e.printStackTrace();
      }
   }

   /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

   /**
     *  return session factory
     *
     */
   public static org.hibernate.SessionFactory getSessionFactory() {
      return sessionFactory;
   }

   /**
     *  return session factory
     *
     *   session factory will be rebuilded in the next call
     */
   public static void setConfigFile(String configFile) {
      HibernateSessionFactory.configFile = configFile;
      sessionFactory = null;
   }

   /**
     *  return hibernate configuration
     *
     */
   public static Configuration getConfiguration() {
      return configuration;
   }

}


Top
 Profile  
 
 Post subject: Re: Hibernate creates wrong Statement
PostPosted: Thu Aug 13, 2009 10:03 am 
Expert
Expert

Joined: Tue May 13, 2008 3:42 pm
Posts: 919
Location: Toronto & Ajax Ontario www.hibernatemadeeasy.com
Thanks for the postback! I actually had a similar problem which I think this will help address. :)

_________________
Cameron McKenzie - Author of "Hibernate Made Easy" and "What is WebSphere?"
http://www.TheBookOnHibernate.com Check out my 'easy to follow' Hibernate & JPA Tutorials


Top
 Profile  
 
 Post subject: Re: Hibernate creates wrong Statement
PostPosted: Fri Aug 14, 2009 3:16 am 
Newbie

Joined: Thu Aug 13, 2009 4:52 am
Posts: 12
Cameron McKenzie wrote:
Thanks for the postback! I actually had a similar problem which I think this will help address. :)



you're welcome ;)
i'm glad that other people can benefit from my posts :)


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.