Question

I am using Hibernate and Struts2. Also, I have my DB in DBForge Studio for MySQL.

What I want to do is to load an object ("product" for example) with the information from several tables. Lets say I have foreing keys refering to them using IDs. In short, how to create views of several tables with Hibernate.

Any idea?

Was it helpful?

Solution 3

Can be done in these simple step.

Step 1.

Create a Class with all the variables you need

Step 2.

Create a constructor with all the variables as parameter, like

className(String name,int rollNUmber){
this.name=name;
this.rollNumber=rollNumber;
}

Step 3

Execute this query

select new com.path.ClassName(columnName1,columnName2) from tableName where Conditions;

NB They type of the value returned(column) from the query must fit into the constructor argument.

OTHER TIPS

In short, you don't. AFAIK, there is no way to create a DB views using Hibernate or JPA.

You can either use simple projection queries, joining over the entities:

select a.x, b.y
from A a join B b where a.z = b.z

or map the result to a DTO by using the NEW operator:

select new com.acme.MyDto(a.x, b.y)
from A a join B b where a.z = b.z

If you have a DB view already, you can map it to a regular entity class and query for this entity.

Example from JAVA Persistence Api book.

@Entity @org.hibernate.annotations.Immutable 
@org.hibernate.annotations.Subselect(
    value = "select i.ID as ITEMID, i.ITEM_NAME as NAME, " + 
            "count(b.ID) as NUMBEROFBIDS " +
            "from ITEM i left outer join BID b on i.ID = b.ITEM_ID " + 
            "group by i.ID, i.ITEM_NAME")
@org.hibernate.annotations.Synchronize({"Item", "Bid"})
public class ItemBidSummary {

@Id
protected Long itemId;

protected String name; 

protected long numberOfBids;

public ItemBidSummary() { }

// Read methods... // ...
}
ItemBidSummary itemBidSummary = em.find(ItemBidSummary.class, ITEM_ID);

// will produce
// select * from (
//     select i.ID as ITEMID, i.ITEM_NAME as NAME, ...
// ) where ITEMID = ?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top