My current job decided to build web based database maintenance system using Struts and Hibernate. The table mapping document xml file, which I will refer to it as “table config file”, basically contains most of the information you’d want about your database. So instead of creating another configuration, I’ve decided to find out if there is a way to access them programmatically in Java. XML configuration elements that I was interested in was the column name and Javabean method name. Here is an example of table config file:
<hibernate-mapping>
<class name=”com.myPojo” table=”MY_TABLE_NAME”>
<property name=”FirstName” type=”string” column=”FIRST_NAME”/>
<property name=”LastName” type=”string” column=”LAST_NAME”/>
</class>
</hibernate-mapping>
the property “name” attribute refers to your mapping POJO’s method. In my example above, myPojo.java will have getter and setter methods defined as “getFirstName(), setFirstName(), getLastName(), setLastName()”.
What I’m interested in is the value of name attribute and value of column attribute. Here are the Java code that will access the values
I’ve created a Configuration object called config by calling “new Configuration().configure();”
Value of “column” attribute:
-
Get the PersistentClass object:
PersistentClass pc = config.getClassMapping(myPojo.class.getName());
-
Get the Table object from the PersistentClass object you just got:
Table tbl = pc.getTable();
Once you have the table object, you can get the list of defined column names using this syntax:
Iterator it = tbl.getColumnIterator();
Value of “name” attribute:
-
Get the Component object out using similar code syntax:
Component cmp = config.getClassMapping(myPojo.class.getName()).getKey();
-
Get the Property iterator:
Iterator it = cmp.getPropertyIterator();
-
You can access the value of name attribute by casting each items in the iteratory with Property calss.
while (it.hasNext()) {
( (Property) it.next() ).getName();
}
I know this is all that of a new information but I found this extremely helpful. I hope you guys find this info helpful as well.
As always, using Hibernate API documentation is awesome!
Happy coding guys.