Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate joining two table and fetch all records?

I have two entity class Category and Events.I need to join both the tables and fetch all records which matching the given condition

My sql query for this

SELECT * FROM category c  inner join `events` e on e.category_i=c.category_id where c.parent_category_id=1;

How i can convert this sql query to hql and fetch the data ? I tried below but not getting the result ? Am very new to hibernate

Events entity class for hibernate mapping

import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;

/**
 * The persistent class for the user database table.
 *
 */
@Entity
@Table(name = "events")
public class Events implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "event_id")
    private int eventId;

    @Column(name = "event_name")
    private String eventName;

    @Column(name = "event_description")
    private String eventDescription;

    @Column(name = "category_i")
    private Integer categoryI;






    public Integer getCategoryI() {
        return categoryI;
    }

    public void setCategoryI(Integer categoryI) {
        this.categoryI = categoryI;
    }

    @Column(name = "is_trending_event")
    private Integer isTrendingEvent;

    @Column(name = "image_url")
    private String imageUrl;

    private Integer status;

    @Column(name = "created_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date createdDate;

    @Column(name = "last_updated_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date lastUpdatedDate;

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public Date getLastUpdatedDate() {
        return lastUpdatedDate;
    }

    public void setLastUpdatedDate(Date lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }

    public int getEventId() {
        return eventId;
    }

    public void setEventId(int eventId) {
        this.eventId = eventId;
    }

    public String getEventName() {
        return eventName;
    }

    public void setEventName(String eventName) {
        this.eventName = eventName;
    }

    public String getEventDescription() {
        return eventDescription;
    }

    public void setEventDescription(String eventDescription) {
        this.eventDescription = eventDescription;
    }



    public Integer getIsTrendingEvent() {
        return isTrendingEvent;
    }

    public void setIsTrendingEvent(Integer isTrendingEvent) {
        this.isTrendingEvent = isTrendingEvent;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

}

Category entity

import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;

/**
 * The persistent class for the user database table.
 *
 */
@Entity
@Table(name = "category")
public class Category implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id")
    private int categoryId;

    @Column(name = "category_name")
    private String categoryName;

    @Column(name = "parent_category_id")
    private Integer parentCategoryId;

    @Column(name = "created_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date createdDate;

    @Column(name = "last_updated_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date lastUpdatedDate;


    @ManyToOne
    @JoinTable(name="events", joinColumns = @JoinColumn(name="category_i"))
    private Events events;

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public Integer getParentCategoryId() {
        return parentCategoryId;
    }

    public void setParentCategoryId(Integer parentCategoryId) {
        this.parentCategoryId = parentCategoryId;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public Date getLastUpdatedDate() {
        return lastUpdatedDate;
    }

    public void setLastUpdatedDate(Date lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }

}

Fetch category method

public List<Object[]> getCategoryList(int id) throws SQLException, ClassNotFoundException, IOException {
        List<Object[]> groupList = null;
        try {
            Session session = sessionFactory.getCurrentSession();
            Query query = session.createQuery("select e from Category e inner join e.events where e.parentCategoryId=1");
            //query.setParameter("id", id);
            groupList = query.list();
        } catch (Exception e) {
        }
        return groupList;
    }
like image 644
Stella Avatar asked Jul 20 '15 05:07

Stella


People also ask

How can we join multiple tables in Hibernate criteria?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.

Can we use joins in Hibernate?

In JPQL, you can define a JOIN statement based on a specified association between 2 entities. Your persistence provider, e.g., Hibernate, translates this into an SQL JOIN statement. The SQL JOIN statement tells the database to combine the columns of 2 tables to a set which you can use within the same query.

What is aggregation in Hibernate?

Overview. Hibernate aggregate functions calculate the final result using the property values of all objects satisfying the given query criteria. Hibernate Query Language (HQL) supports various aggregate functions – min(), max(), sum(), avg(), and count() in the SELECT statement.

How do I join two tables in HQL?

We can apply the Joins in Hibernate by using the HQL query or native SQL query. To make a join between the two tables, the two tables must be in a logical relationship. We can achieve the relationship between two tables by applying the parent table's primary key as a child table's foreign key.


2 Answers

You need to think in terms of Java objects when using ORM tools.

From your question I think the query that you're trying to write will look something like:

public List<Category> getCategoryList(int id) {
    List<Category> groupList;
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("select c from Category c join fetch c.events where c.parentCategory.categoryId = 1");
    //query.setParameter("id", id);
    groupList = query.list();
    return groupList;
}

One of the benefits of using an ORM is that it works out the full join query for you.

For this to work you need to update your class model as follows:

import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;

@Entity
@Table(name = "events")
public class Event implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "event_id")
    private int eventId;

    @Column(name = "event_name")
    private String eventName;

    @Column(name = "event_description")
    private String eventDescription;

    @ManyToOne
    @JoinColumn(name = "category_i")
    private Category category;

    @Column(name = "is_trending_event")
    private Integer isTrendingEvent;

    @Column(name = "image_url")
    private String imageUrl;

    private Integer status;

    @Column(name = "created_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date createdDate;

    @Column(name = "last_updated_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date lastUpdatedDate;

    ...

}

and

import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;

@Entity
@Table(name = "category")
public class Category implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id")
    private int categoryId;

    @Column(name = "category_name")
    private String categoryName;

    @ManyToOne
    @JoinColumn(name="parent_category_id")
    private Category parentCategory;

    @Column(name = "created_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date createdDate;

    @Column(name = "last_updated_date")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date lastUpdatedDate;

    @OneToMany(mappedBy="category")
    private List<Event> events;

    ...

}
like image 126
Steve C Avatar answered Oct 26 '22 16:10

Steve C


Hibernate is about mapping objects and the relations, however you are mapping simple id fields.

In your Events class you have the followingL

@Entity
@Table(name = "events")
public class Events implements Serializable { 

    @Column(name = "category_i")
    private Integer categoryI;

}

However it should be a Category instead of an Integer.

@Entity
@Table(name = "events")
public class Events implements Serializable { 

    @ManyToOne
    @Column(name = "category_i")
    private Category category;

}

Then in your Category you should add the mappedBy field to the @ManyToOne on the events field and remove the @JoinColumn.

@Entity
@Table(name = "category")
public class Category implements Serializable {

    @OneToMany(mappedBy="category")
    private Events events;
}

The same applies to the parentCategoryId of the Category class.

Now that you have your mapping corrected you should be able to write the query as you wanted to.

like image 3
M. Deinum Avatar answered Oct 26 '22 17:10

M. Deinum