Some important question about JPA!!!
Hi there, I have a web application written in Java 1.4
I want to move this to Java 1.5 using JPA but after review old code I've got some stuck:
1. This application have a function that get Lists from a table:
Collection getList(String className, string tableName)
That do follwing tasks:
Get set of properties from class schema (by className)
Get record set from table
Each row of record set do:
- Create object and set properties value from column that named the same name of property.
- Add object to collection
Return collection
As my knowledge, in JPA, each entity class schema is mapped with a table schema. So, this function can't migrate. But in my application case, there are about 50 tables, mapping entities to each table is not good idea. Is there another solution?
2. In database design, a table have composite PKs that merge from many part, each part is a property of entity too, for example table User have column User_ID = Agency_ID + Deparment_ID + SeqNum. How I can map Agency and Department properties of User entity to the table User?
Please help me, thanks
Thank you.
[1180 byte] By [
wangld7xa] at [2007-11-27 11:40:01]

# 2
Hi uvnet,
I think the old code can run in java 1.5 with a minor change but the problem is I want take advantage of using 1.5 especially JPA (big change :D ).
Anyway, the sample code would be:
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class DAO {
public Collection getList(String className, String tableName, int encoding) {
Object objDescriber = null;
ResultSet rs = null;
Map map = null;
Iterator properties = null;
ArrayList<Object> returnValue = new ArrayList<Object>();
try {
objDescriber = (Object)Class.forName(className).newInstance();
try {
map = BeanUtils.describe(objDescriber);
properties = map.keySet().iterator();
//Get ResultSet from Table
rs = getResultSet(tableName);
while (rs.next()) {
while (properties.hasNext()) {
String name = (String) properties.next();
String typeName = PropertyUtils.getPropertyType(objDescriber, name).getName();
//Get value from current row and column name of ResultSet
Object value = getValue(rs, name, encoding);
try {
Object obj = (Object)Class.forName(className).newInstance();
PropertyUtils.setProperty(obj, typeName, value);
returnValue.add(obj);
}
catch (Exception ex) {
}
}
}
}
catch (Exception ex) {
}
}
catch (Exception ex) {
}
return returnValue;
}
}