Hibernate加入两个表并获取所有记录?

时间:2015-07-20 05:50:23

标签: java mysql spring hibernate

  

我有两个实体类Category和Events。我需要连接两个表并获取与给定条件匹配的所有记录

我的SQL查询

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

如何将此sql查询转换为hql并获取数据?我试过下面但没有得到结果?对于休眠是非常新的

  

用于hibernate映射的事件实体类

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;
    }

}
  

类别实体

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;
    }

}
  

获取类别方法

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;
    }

4 个答案:

答案 0 :(得分:6)

使用ORM工具时,您需要考虑Java对象。

根据您的问题,我认为您尝试编写的查询类似于:

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;
}

使用ORM的一个好处是它可以为您完成整个连接查询。

为此,您需要更新您的班级模型,如下所示:

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;

    ...

}

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;

    ...

}

答案 1 :(得分:3)

Hibernate是关于映射对象和关系,但是您要映射简单的id字段。

Events课程中,您有以下内容

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

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

}

但它应该是Category而不是Integer

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

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

}

然后在您的Category中,您应该将mappedBy字段添加到@ManyToOne字段的events,然后移除@JoinColumn

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

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

这同样适用于parentCategoryId类的Category

现在您已经更正了映射,您应该可以根据需要编写查询。

答案 2 :(得分:0)

此查询应该完成这项工作:

from Category as c
inner join c.events as e
where c.parentCategoryId = 1

另外,你似乎有一个拼写错误(最后缺少“d”):

@JoinColumn(name="category_i"))

答案 3 :(得分:0)

以下代码

public List<Object[]> getCategoryList(int id) throws SQLException, ClassNotFoundException, IOException {


        Session session = sessionFactory.getCurrentSession();
        return session.createCriteria(Catagory.class)
        .setFetchMode("events", FetchMode.JOIN)
        .add(Restrictions.eq("parentCatagoryId", 1))
        .list();

}

希望这些东西有效。