-->
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.  [ 4 posts ] 
Author Message
 Post subject: Hibernate and Postgres and case sensitivity and persistance
PostPosted: Thu Aug 10, 2006 6:32 pm 
Newbie

Joined: Thu Aug 10, 2006 12:25 am
Posts: 13
Hi

Been doning some searching to find the answer to how to deal with case sensitivity when using postgres and hibernate. I have a database that is already created that uses mixed case tables names and column names. When I try and map this with hibernate i use the backtick as suggested in the documentation.

I have started to do some testing

UserInfo.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="com.hibernatebook.chap1.UserInfo" table="`UserInfo_TBL`">
      <id name="userID" column="`userID`" type="java.lang.Long" unsaved-value="0">
         <generator class="identity"/>
      </id>
      <property name="firstName" column="`firstName`" type="java.lang.String"/>
      <property name="lastName" column="`lastName`" type="java.lang.String"/>
      <property name="age" column="`age`" type="java.lang.Integer"/>
   </class>
</hibernate-mapping>


hibernate.properties
Code:
######################
### Query Language ###
######################
## Define query language constants / function names
hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'
## Package imports
hibernate.query.imports net.sf.hibernate.test, net.sf.hibernate.eg
## MySQL
#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.connection.driver_class org.gjt.mm.mysql.Driver
#hibernate.connection.url jdbc:mysql://localhost/Chap1DB
#hibernate.connection.username hibernate
#hibernate.connection.password hibernate
hibernate.dialect org.hibernate.dialect.PostgreSQLDialect
hibernate.connection.driver_class org.postgresql.Driver
hibernate.connection.url jdbc:postgresql://postgres/Chap1DB
hibernate.connection.username hibernate
hibernate.connection.password password
#################################
### Hibernate Connection Pool ###
#################################
hibernate.connection.pool_size 1
hibernate.statement_cache.size 25
##############################
### Miscellaneous Settings ###
##############################
## Print all generated SQL to the console
hibernate.show_sql true
## Set the maximum JDBC 2 batch size (a nonzero value enables batching)
hibernate.jdbc.batch_size 0
## Use streams when writing binary types to / from JDBC
hibernate.jdbc.use_streams_for_binary true
##
## Mine
hibernate.hbm2ddl.auto update


UserInfo.java
Code:
package com.hibernatebook.chap1;
public class UserInfo implements java.io.Serializable
{
   private Long userID;
   private String firstName;
   private String lastName;
   private Integer age;

   public String toString()
   {
      return "UserInfo (UserID=" + userID + " First Name=" + firstName + " Last Name=" + lastName   + " Age=" + age + ")";
   }
   public void setUserID(Long userID)
   {
      this.userID = userID;
   }
   public Long getUserID()
   {
      return userID;
   }
   public void setFirstName(String firstName)
   {
      this.firstName = firstName;
   }
   public String getFirstName()
   {
      return firstName;
   }
   public void setLastName(String lastName)
   {
      this.lastName = lastName;
   }
   public String getLastName()
   {
      return lastName;
   }
   public void setAge(Integer age)
   {
      this.age = age;
   }
   public Integer getAge()
   {
      return age;
   }
}


UserInfoMain.java
Code:
package com.hibernatebook.chap1;
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
public class UserInfoMain
{

   public static void addUser(String fname, String lname, int Iage)
   {
         UserInfo userInfo = new UserInfo();
         userInfo.setFirstName(fname);
         userInfo.setLastName(lname);
         userInfo.setAge(new Integer(Iage));
         Session session = ConnectionFactory.getInstance().getSession();


         try
         {
            session.beginTransaction();
            session.save(userInfo);
            System.err.println("commit");
            session.getTransaction().commit();
            session.flush();
         }
         catch (Exception e)
         {
            System.err.println("Hibernate Exception" + e.getMessage());
         }
         finally
         {
            if (session != null)
            {
               try
               {
                  session.close();
               }
               catch (Exception e)
               {
                  System.err.println("Hibernate Exception" + e.getMessage());
               }

            }
         }
   }
   
   public static void getUsers()
   {
      Session session = ConnectionFactory.getInstance().getSession();
      try
      {
         Query query = session.createQuery("select userinfo from com.hibernatebook.chap1.UserInfo   userinfo order by userinfo.userID");
         java.util.List userlist = query.list();
         Iterator itr = userlist.iterator();
         while (itr.hasNext())
         {
            UserInfo user = (UserInfo)itr.next();
            System.out.println(user.getUserID()+"\t\t"+user.getFirstName()+"\t\t"+user.getLastName() +"\t\t"+ user.getAge());
         }
      }
      catch (HibernateException e)
      {
         System.err.println("Hibernate Exception" + e.getMessage());
      }
      finally
      {
         if (session != null)
         {
            try
            {
               session.close();
            }
            catch (HibernateException e)
            {
               System.err.println("Hibernate Exception" + e.getMessage());
            }
         }
      }
   }

   public static void main(String[] args)
   {
      if (args.length !=0)
      {
         String fname = args[0];
         String lname = args[1];
         String age = args[2];
         int Iage = Integer.parseInt(age.trim());

/*
         System.err.println("Were are here"
                        + " fname ["+fname+"]"
                        + " lname ["+lname+"]"
                        + " Iage  ["+Iage+"]" );
*/

         addUser(fname, lname, Iage);
      }
      System.out.println("\n\nThe List of Users:\n");
      getUsers();
   }
}


ConnectionFactory.java
Code:
package com.hibernatebook.chap1;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* This is session Singleton class that is used to create and return the Hibernate Session.
*
*/
public class ConnectionFactory
{
   private static ConnectionFactory connFctry = null;
   private SessionFactory sessionFactory = null;
   private ConnectionFactory()
   {
      try
      {
         Configuration cfg = new Configuration().addClass(UserInfo.class);
         sessionFactory = cfg.buildSessionFactory();
      }
      catch (MappingException e)
      {
         System.err.println("Mapping Exception" + e.getMessage());
         throw new RuntimeException(e);
      }
      catch (HibernateException e)
      {
         System.err.println("Hibernate Exception" + e.getMessage());
         throw new RuntimeException(e);
      }
   }
   /**
   * This method is used to return the connFctry of the ConnectionFactory class.
   */
   public static synchronized ConnectionFactory getInstance()
   {
      if (connFctry == null)
      {
         connFctry = new ConnectionFactory();
      }
      return connFctry;
   }
   /**
   * This method is used to return the Hibernate session.
   */
   public Session getSession()
   {
      try
      {
         Session session = sessionFactory.openSession();
         return session;
      }
      catch (Exception e)
      {
         System.err.println("Hibernate Exception" + e.getMessage());
         throw new RuntimeException(e);
      }
   }
}


I have taken this example through a book I am reading about hibernate.

when I run it this is what I end up with
[java] Hibernate: insert into "UserInfo_TBL" ("firstName", "lastName", "age") values (?, ?, ?)
[java] Hibernate: select currval('"UserInfo_TBL"_"userID"_seq')
[java] Hibernate Exceptioncould not insert: [com.hibernatebook.chap1.UserInfo]


[java] The List of Users:

[java] Hibernate: select userinfo0_."userID" as userID1_0_, userinfo0_."firstName" as firstName2_0_, userinfo0_."lastName" as lastName3_0_, userinfo0_."age" as age4_0_ from "UserInfo_TBL" userinfo0_ order by userinfo0_."userID"
[java] Hibernate Exceptioncould not execute query

Is this a problem with my example am I missing something ?

One other thing I had a problem with, is the example originally did not have the begin transactio and commit. It was based against MSQL. If I am making an object persistant do I have to do the begintransaction and commit everywere ?

Thanks


Top
 Profile  
 
 Post subject: Update
PostPosted: Thu Aug 10, 2006 6:56 pm 
Newbie

Joined: Thu Aug 10, 2006 12:25 am
Posts: 13
I have tried changing my generator class from identity to sequence and it started to work. Taking a closer look at the sql generated

[java] Hibernate: select currval('"UserInfo_TBL"_"userID"_seq')

There seems to be a mix up in the nameing with double quoting !

Is this a bug ? if so where would I look for this ?

Alex


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 10, 2006 9:32 pm 
Newbie

Joined: Thu Aug 10, 2006 12:25 am
Posts: 13
Sorry missing leading with the last one post.

The select is also failing

[java] Hibernate Exceptioncould not execute query
[java] Hibernate: select userinfo0_."userID" as userID1_0_, userinfo0_."firstName" as firstName2_0_, userinfo0_."lastName" as lastName3_0_, userinfo0_."age" as age4_0_ from "UserInfo_TBL" userinfo0_ order by userinfo0_."userID"

which is strange cause when I paste this into psql it returns values!

but this is only when generator is set to sequence not identity!!!


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 10, 2006 9:54 pm 
Newbie

Joined: Thu Aug 10, 2006 12:25 am
Posts: 13
Okay I have found

public String getIdentitySelectString(String table, String column, int type) {
return new StringBuffer().append("select currval('")
.append(table)
.append('_')
.append(column)
.append("_seq')")
.toString();
}


Which doesn't seem to take into account that the components are quoted

It would be nice to be able to name the identity seq like you can with sequence


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 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.