This is in continuation to my post "Mapping the sql table and java object in runtime".
I have figured out that we can map a single POJO to different classes at runtime. The way i am doing it is
Code:
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("select c from test.Cat as c where c.sex = 'F'");
for (Iterator it = query.iterate(); it.hasNext();) {
Cat cat = (Cat) it.next();
String fileName = getServletContext().getRealPath("/WEB-INF/classes")+"\\ClientTable.hbm.xml";
FileWriter fw = new FileWriter( new File(fileName));
fw.write("<?xml version=\"1.0\"?> \n");
fw.write("<!DOCTYPE hibernate-mapping \n" +
" PUBLIC \"-//Hibernate/Hibernate Mapping DTD//EN\"\n" +
" \"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd\">\n");
fw.write("<hibernate-mapping>\n");
fw.write(" <class name=\"test.ClientTable\" table=\""+cat.getName()+"\">\n");
fw.write(" <id name=\"col1\" type=\"string\" unsaved-value=\"null\" >\n");
fw.write(" <column name=\""+cat.getSex()+"\" sql-type=\"char(10)\" not-null=\"true\"/> \n");
fw.write(" <generator class=\"assigned\"/>\n");
fw.write(" </id>\n");
fw.write(" <property name=\"col2\">\n");
fw.write(" <column name=\"val\" sql-type=\"char(10)\" not-null=\"true\"/>\n");
fw.write(" </property>\n");
fw.write(" </class>\n");
fw.write("</hibernate-mapping>\n");
fw.close();
Configuration cfg = new Configuration().configure();
cfg = cfg.addFile(new File(fileName));
SessionFactory sf = cfg.buildSessionFactory();
Session session2 = sf.openSession();
Transaction tx2 = session2.beginTransaction();
Query query2 = session2.createQuery("from test.ClientTable");
out.println("table 2 contents Begin:");
for (Iterator it2 = query3.iterate(); it2.hasNext();) {
ClientTable ct2 = (ClientTable) it2.next();
out.println(" values of second table : " + ct2.getCol1() + " :: " + ct2.getCol2() );
}
out.println("table 2 contents END:");
tx2.commit();
}
tx.commit();
HibernateUtil.closeSession();
As you can observe I have to create a new xml file, configuration, sessionfactory and session for every result of the first query. some fine tuning of code can be done to this raw code for perfomance, but the basic idea remains the same. i.e. create a new configuration and sessionfactory
I tried to use the same configuration, but as all the tables are using the same POJO, it is throwing a 'MappingException: duplicate import' error.
In my application, once the query is processes, i do not require that mapping anymore. so is there a way where in i can remove a mapping from the configuration, and use the same configuration to map it again to a different table which uses the same java class?
and The basic question is: "IS my approach correct OR is there a better way to do it??"