Wednesday, 24 October 2012

Hibernate query across multiple tables

In order to query across multiple tables of the same type (siblings who share a parent) in hibernate you need to add
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) on the Paren class. Heres an example.

First define the parent domain object
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Vehicle
{ //some code }


Now define the entities
@Entity
@Table(name="CARS")
public class Car extends Vehicle{ //some code }

@Entity
@Table(name="BIKES")
public class Bike extends Vehicle{ //some code }

Now to get all vehicles whether there are cars or bikes.

List<Vehicle> vehicles = sessionFactory
                               .getSession()
                                 .createCriteria(Vehicle.class)
                                   .list();


The above will query tables of objects that extend the parent class, to return vehicles.

No comments:

Post a Comment