javahibernatejpasessionfactory

Retrieve primary key from entity class from sessionfactory in hibernate


I am creating one SessionFactory using hibernate and I need the primary key of all the tables associated with the entity classes generated from the SessionFactory. Is there any way to achieve this?

I have created SessionFactory and from the gathered the ClassMetaData. But unable to retrieve the primary key from the ClassMetaData.


Solution

  • I don't know which Hibernate version you have. This works for version 4.2.x:

    Configuration con = // get the org.hibernate.cfg.Configuration
    for(Iterator<PersistentClass> itpc = con.getClassMappings();itpc.hasNext();)
    {
        PersistentClass pc = itpc.next();
        System.out.println(pc.getEntityName() + ", " + pc.getNodeName());
        System.out.println("Identifier(s):");
        Property idpy = pc.getIdentifierProperty();
        for(Iterator<?> itpy = idpy.getColumnIterator();itpy.hasNext();)
        {
            Object o = itpy.next();
            if(o instanceof Column)
            {
                Column c = (Column)o;
                System.out.println(c.getName());
            }
        }
    }