Mysql
 sql >> Database >  >> RDS >> Mysql

Sospensione unendo due tabelle e recupera tutti i record?

Devi pensare in termini di oggetti Java quando usi ORM strumenti.

Dalla tua domanda penso che la query che stai cercando di scrivere sarà simile a:

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

Uno dei vantaggi dell'utilizzo di un ORM è che risolve la query di join completo per te.

Affinché funzioni, devi aggiornare il tuo modello di classe come segue:

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;

    ...

}

e

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;

    ...

}