Thursday, June 17, 2010

Iterate over your whole DB using hibernate

In this post I'll assume you already have your hibernate object corresponding to your DB schema.

What will we try to achieve here?
I will iterate all of the DB using hibernate objects, and here is a little java program which will attempt to achieve just that:

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.metadata.ClassMetadata;

import java.util.Map;

/**
* Created by IntelliJ IDEA.
* User: avih
* Date: May 11, 2010
* Time: 7:43:37 AM
*/
public class Main {
private static final SessionFactory ourSessionFactory;

static {
try {
ourSessionFactory = new AnnotationConfiguration().
configure("hibernate.cfg.xml").
buildSessionFactory();
}
catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}

public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}

public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
System.out.println("querying all the managed entities...");

final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
for (Object key : metadataMap.keySet()) {
final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
final String entityName = classMetadata.getEntityName();
final Query query = session.createQuery("from " + entityName);
System.out.println("executing: " + query.getQueryString());

int index = 0;
for (Object o : query.list()) {
index++;
//System.out.println("index: " + o);
}
System.out.println("Contains " + index + " Objects\n");
}
}
finally {
session.close();
}
}
}

No comments: