hari-p
4/12/2017 - 1:48 AM

Hibernate get child object count: @Formula("(select count(*) from collection_items ci where ci.collection_id = id)") private int numb

Hibernate get child object count:

@Formula("(select count(*) from collection_items ci where ci.collection_id = id)") private int numberOfItems;

here the table name is not hibernate name but the original name of the table

package au.edu.esa.scis.entities;

import au.edu.esa.scis.enums.CollectionStatus;
import org.hibernate.annotations.Formula;

import javax.persistence.*;

/**
 * Created by hveluchamy on 10/04/2017.
 */
@Entity
@Table(name="collections")
public class CollectionData {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(name = "collection_category_id")
    private Long collectionCategoryId;

    @Formula("(select count(*) from collection_items ci where ci.collection_id = id)")
    private int numberOfItems;


    @Enumerated(EnumType.STRING)
    @Column(name = "status")
    private CollectionStatus status;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



    public CollectionStatus getStatus() {
        return status;
    }

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

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /*public List<CollectionItem> getCollectionItems() {
        return collectionItems;
    }

    public void setCollectionItems(List<CollectionItem> collectionItems) {
        this.collectionItems = collectionItems;
    }
*/
    public Long getCollectionCategoryId() {
        return collectionCategoryId;
    }

    public void setCollectionCategoryId(Long collectionCategoryId) {
        this.collectionCategoryId = collectionCategoryId;
    }

    public int getNumberOfItems() {
        return numberOfItems;
    }

    public void setNumberOfItems(int numberOfItems) {
        this.numberOfItems = numberOfItems;
    }
}