Reputation: 1703
I using the following code to get data from the JPA but the read call can be for any entity (dynamic call),since the result list is generic but the structure is always the same like this result
Person [firstName=firstName 1, lastName=lastName 1, bigDecimal=0, myDate=Wed Sep 16 06:42:18 IST 1998],
Person [firstName=firstName 2, lastName=lastName 2, bigDecimal=0, myDate=Sun May 19 13:12:51 IDT 1957],
Person [firstName=firstName 3, lastName=lastName 3, bigDecimal=0, myDate=Fri Jun 03 05:09:20 IDT 1949],
The result here is for person but it can be for every entity and the result be with exactly the same structure like entityname(here is person) and key val like firstname is the key and the val is firstname1 etc
How can i print it from result list like name of the entity and list of key value with the respective data?
This is the code that im using to get the data.
factory = Persistence.createEntityManagerFactory("abc");
EntityManager entityManager = factory.createEntityManager();
Query query = entityManager.createQuery("SELECT p FROM " + className + " p");
List resultList = query.getResultList();
I cannot use definition like List<Person> resultList
because this is related to just Person and during RT I can get any entity like customer ,address,sales order etc .(all the entities is type JPA class) and have the class name and the prosperites of the class name and value
for example here the class is
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private String firstName;
private String lastName;
Upvotes: 0
Views: 1219
Reputation: 3707
You can make a generic String utility that uses reflection to build a string representation of any object. You would get the list of fields with something like:
List result = new ArrayList();
Field[] f = <your object>.getClass().getDeclaredFields();
for (int i = 0; i < f.length; i++) {
if (!Modifier.isStatic(f[i].getModifiers())) {
result.add(f[i]);
}
}
return result.iterator();
and then for each field do something like:
try {
field.setAccessible(true);
Object value = field.get(<your object>);
<String buffer of your generic toString representation>.append(value);
} catch (IllegalAccessException e) {
// e.printStackTrace() obviously
}
UPDATE
Or, if you like libraries, you can use the ReflectionToStringBuilder from Apache Commons Lang. I don't know if the default ToStringStyle is what you need, but it's probably easy enough to subclass.
Upvotes: 2
Reputation: 10342
If you want to print the data in console/log, I think it's as easy as Override the toString()
method in the Person class.
Upvotes: 3