How to use Reflection to Document your Data Model based on JPA Annotations

So using JPA, Hiber­nate or EBeans is cool when you can just anno­tate your Java classes, but haven’t you always wished you could “gen­er­ate” doc­u­men­ta­tion of your data model from the code? Pulling infor­ma­tion of the the JPA / Hiber­nate  and other val­i­da­tion annotations?

Assum­ing you have all those nice Anno­ta­tions in your beans:
 
 
 
 
 

@Entity
@Table(name = "project_bills")
public class Bill extends Model {

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name="PBI_ID")
	public Long id;

	@DoubleFormat
	@Column(name="PBI_BILL_AMOUNT",length=22)
	public Double billAmount;

	@Column(name="PBI_BILL_DATE")
	@DateTime(pattern="dd.MM.yyyy")
	public Date billDate;

	@Column(name="PBI_BILL_NUMBER",length=10)
	public String billNumber;

	@Column(name="PBI_CAN_BILL")
	public Boolean canBill;

	@Column(name="PBI_COMMENT",length=65535)
	public String comment;

	@Column(name="PBI_PAID_DATE")
	@DateTime(pattern="dd.MM.yyyy")
	public Date paidDate;

Here is an exam­ple of how to go about accom­plish­ing that task:

public static String listEntities(String _package) {
        StringBuffer retval = new StringBuffer();
        Reflections reflections = new Reflections(_package, Play.application().classloader());
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);
        for (Class c : classes) {
            retval.append(c.getName() + "\n");
            retval.append(listAnnotations(c.getName()) + "\n\n");
            retval.append(listAttributes(c.getName()) + "\n\n");
        }
        return retval.toString();
    }

    public static String listAnnotations(String _class) {
        StringBuffer retval = new StringBuffer();
        try {
            Annotation[] annotations = Class.forName(_class).getAnnotations();
            if (annotations.length != 0) {
                for (int j = 0; j < annotations.length; j++) {
                    retval.append(annotations[j].toString() + ": " + annotations[j].annotationType() + "\n");
                }
                retval.append("\n");
            }
        } catch (ClassNotFoundException e) {
            System.out.println(e.toString());
            return retval.toString();
        }
        return retval.toString();
    }

    public static String listAttributes(String _class) {
        StringBuffer retval2 = new StringBuffer();
        boolean perstistent = false;
        try {
            for (Field field : Class.forName(_class).getDeclaredFields()) {
                Class type = field.getType();
                String name = field.getName();
                perstistent = false;
                StringBuffer retval = new StringBuffer();
                retval.append("\t" + name + " (" + type + ")\n");
                Annotation[] annotations = field.getDeclaredAnnotations();

                if (annotations.length != 0) {
                    for (int j = 0; j < annotations.length; j++) {
                        retval.append(annotations[j].toString() + ": " + annotations[j].annotationType() + "\n");
                        if (annotations[j].toString().startsWith("@javax.persistence")) {
                            perstistent = true;
                        }
                    }
                    retval.append("\n");
                }
                if (perstistent) {
                    retval2.append(retval);
                }
            }
        } catch (ClassNotFoundException e) {
            System.out.println(e.toString());
            return retval2.toString();
        }
        return retval2.toString();
    }

Which will gen­er­ate some­thing like this:

models.controlling.Bill
@javax.persistence.Table(schema=, uniqueConstraints=[], catalog=, name=project_bills): interface javax.persistence.Table
@javax.persistence.Entity(name=): interface javax.persistence.Entity

	id (class java.lang.Long)
@javax.persistence.Id(): interface javax.persistence.Id
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_ID, updatable=true, length=255, nullable=true, table=): interface javax.persistence.Column

	billAmount (class java.lang.Double)
@utils.data.formatters.Formats$DoubleFormat(): interface utils.data.formatters.Formats$DoubleFormat
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_BILL_AMOUNT, updatable=true, length=22, nullable=true, table=): interface javax.persistence.Column

	billDate (class java.util.Date)
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_BILL_DATE, updatable=true, length=255, nullable=true, table=): interface javax.persistence.Column
@play.data.format.Formats$DateTime(pattern=dd.MM.yyyy): interface play.data.format.Formats$DateTime

	billNumber (class java.lang.String)
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_BILL_NUMBER, updatable=true, length=10, nullable=true, table=): interface javax.persistence.Column

Of course this is only the tip of the ice­berg, but you get the idea.
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


seven + = 11



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close