-->
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: Rename table name in mapping at runtime
PostPosted: Wed Aug 08, 2007 10:21 am 
Newbie

Joined: Sun May 06, 2007 5:57 am
Posts: 10
I have several tables with the same structure and I'd like to use only one mapping file. So I want to switch between the tables.

I've found the following solution, but I'm not satisfied yet:
Code:
   SessionFactory sessionFactory;
   Configuration configuration;
   try{
      configuration = new Configuration()
                      .configure("mysql.cfg.xml");
      Iterator iterator = configuration.getTableMappings();         
      while (iterator.hasNext()) {
         Table table = (Table) iterator.next();   
         if (table.getName().equals("TEST")) {
            table.setName("TEST2");
                           
         }
         System.out.println(table.getName());
      }     
      sessionFactory = configuration
                  .buildSessionFactory();
   }
   catch(Throwable ex){
      throw new ExceptionInInitializerError(ex);         
   }


For this solution I need to remember the changed table name. I think, it's more confortable to use the name of the mapped POJO. I tried to use following code, but it doesn't work:

Code:
   SessionFactory sessionFactory;
   Configuration configuration;
   try{
      configuration = new Configuration()
                      .configure("mysql.cfg.xml");
         Iterator iterator = configuration.getClassMappings();         
         while (iterator.hasNext()) {             
            RootClass rootClass = (RootClass)iterator.next();
            if (rootClass.getClassName().equals("TESTCLASS"))               rootClass.getTable().setName("TESTTABLE");
         }
      sessionFactory = configuration
                  .buildSessionFactory();
   }
   catch(Throwable ex){
      throw new ExceptionInInitializerError(ex);         
   }


There are only few comments in the Hibernate API, so I don't know, how to to better. Is there anyone, who can help me?


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 09, 2007 3:33 am 
Newbie

Joined: Sun May 06, 2007 5:57 am
Posts: 10
Sorry, I did a mistake. The second example works, too.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 17, 2007 3:25 am 
Newbie

Joined: Tue Nov 15, 2005 10:18 am
Posts: 13
Hi,

I have the same problem but i have to change "schema". My source code looks like this but it doesn't work:

Code:
      SessionFactory sessionFactory;
         Configuration configuration;
         try{
           configuration = new Configuration().configure("/hibernate.cfg.xml");
             Iterator iterator = configuration.getClassMappings();         
             while (iterator.hasNext()) {             
               RootClass rootClass = (RootClass)iterator.next();
               System.out.println("&&&&: "+rootClass.getTable().getName());
               if (rootClass.getTable().getName().equals("CHA20P")){
                  rootClass.getTable().setSchema("testschema");
                  sessionFactory = configuration.buildSessionFactory();
                  Charge c=vipModel.getCharge(5910, "27640107123456");
                  break;                           
               }
               
             }
          
         }
         catch(Throwable ex){
           throw new ExceptionInInitializerError(ex);         
         }



who can help me????

Thanks
Vicky


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 17, 2007 4:34 am 
Expert
Expert

Joined: Fri Jul 13, 2007 8:18 am
Posts: 370
Location: london
In what way does this not work? I just tried your code and it seems to do the trick witch DDL generation and insert queries. What problems are you having?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 17, 2007 5:32 am 
Newbie

Joined: Tue Nov 15, 2005 10:18 am
Posts: 13
we have a iSeries-Machine. There are many libraries (schema) in which you can find tables with the same names:

Library lib1 table table1
Library lib2 table table1
Library lib3 table table1

In my application I have to differentiate in which library/table i have to update a dataset. It should be done at runtime.

There is a default value in my mapping file.

Code:
<class
     name="xx.xxx.Charge"
     table="CHA20P"
     schema="map">


If I execute the source code that I've posted it uses the default value (map) and not testschema.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 17, 2007 6:32 am 
Expert
Expert

Joined: Fri Jul 13, 2007 8:18 am
Posts: 370
Location: london
Quote:
If I execute the source code that I've posted it uses the default value (map) and not testschema.

How do you know? Is it in the generated SQL?

I've built a test case which seems to work perfectly.

Here's the generate ddl when I _don't_ manipulate the schema in java:
Code:
11:23:09,453  INFO SchemaExport:36 - Running hbm2ddl schema export
drop table if exists map.CHA20P
create table map.CHA20P (id bigint not null auto_increment, data varchar(255), primary key (id))
11:23:09,453  INFO SchemaExport:36 - schema export complete
Hibernate: insert into map.CHA20P (data) values (?)
11:23:09,546  WARN JDBCExceptionReporter:66 - SQL Error: 1146, SQLState: 42S02
11:23:09,546 ERROR JDBCExceptionReporter:24 - Table 'map.cha20p' doesn't exist

As you can see it fails because its using map.chap20p and map doesn't exist in my db.

If I include the rootClass.getTable().setSchema("test") I get the following:
Code:
11:26:43,859  INFO SchemaExport:36 - Running hbm2ddl schema export
drop table if exists test.CHA20P
create table test.CHA20P (id bigint not null auto_increment, data varchar(255), primary key (id))
11:26:43,859  INFO SchemaExport:36 - schema export complete
Hibernate: insert into test.CHA20P (data) values (?)
Hibernate: select charge0_.id as id0_0_, charge0_.data as data0_0_ from test.CHA20P charge0_ where charge0_.id=?
Hibernate: update test.CHA20P set data=? where id=?

No problem here as "test" is a valid schema.

Here's the code, etc. perhaps it'll be of some help. btw, I'm using hibernate v3.2.5ga.

Charge.java
Code:
package test.renameschema;
public class Charge {
   private Long id;
   private String data;
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
   public String getData() {
      return data;
   }
   public void setData(String data) {
      this.data = data;
   }
}


Charge.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="test.renameschema">
   <class name="Charge" table="CHA20P" schema="map">
       <id name="id">
           <generator class="native"/>
       </id>
      <property name="data"/>
   </class>
</hibernate-mapping>


Test.java
Code:
package test.renameschema;

import junit.framework.TestCase;
import org.hibernate.Session;

public class Test extends TestCase {

   public void testUpdate() {
      createCharge();
      
      Session s = HibernateUtil.getSession();
      s.beginTransaction();
      Charge charge = (Charge)s.load(Charge.class, new Long(1));
      charge.setData("data updated");
      s.update(charge);
      s.getTransaction().commit();
      s.close();
   }

   private void createCharge() {
      Session s = HibernateUtil.getSession();
      s.beginTransaction();
      Charge charge = new Charge();
      charge.setData("data");
      s.save(charge);
      s.getTransaction().commit();
      s.close();
   }
}


HibernateUtil.java
Code:
package test.renameschema;

import java.util.Iterator;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.RootClass;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateUtil {

    private static SessionFactory factory;

    static {
        Configuration configuration;
        try{
          configuration = new Configuration().configure("/hibernate.cfg.xml");
            Iterator iterator = configuration.getClassMappings();
            while (iterator.hasNext()) {             
              RootClass rootClass = (RootClass)iterator.next();
              System.out.println("&&&&: "+rootClass.getTable().getName());
              if (rootClass.getTable().getName().equals("CHA20P")){
                 rootClass.getTable().setSchema("test");
                 setSessionFactory(configuration.buildSessionFactory());
                 break;                           
              }
            }
        }
        catch(Throwable ex){
          throw new ExceptionInInitializerError(ex);         
        }
        // Print generated schema to console
        new SchemaExport(configuration).create(true,false);
    }

    public static synchronized Session getSession() {
        if (factory == null) {
            factory = new Configuration().configure().buildSessionFactory();
        }
        return factory.openSession();
    }

    public static void setSessionFactory(SessionFactory factory) {
        HibernateUtil.factory = factory;
    }
}


hibernate.cfg.xml
Code:
<?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="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/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>

        <property name="show_sql">true</property>
      <property name="hbm2ddl.auto">create-drop</property>

        <mapping resource="test/renameschema/Charge.hbm.xml"/>

   </session-factory>

</hibernate-configuration>


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.