首页 > 解决方案 > 如何从在休眠中有两个嵌套对象的对象中获取对象列表?

问题描述

我有一个产品、位置和产品位置表。检索 Location 对象后,我希望获取属于该位置的所有产品的列表。我尝试设置一个标准,但它返回的是 ProductLocation 对象而不是产品列表。我的问题是如何从 ProductLocation 对象中获取产品列表?

List<Product> findByLocation(Location location){

        def criteria = ProductLocation.where {
            eq('location', location)

        }
        criteria.list()
    }



class Product {

        String title
        String imagepath
        String description
        Category category

        static belongsTo = [locations: Location]

        static mapping = {
            version false
        }

    static constraints = {
        title nullable: false
        imagepath nullable: false
        description nullable: true
    }

    static hasMany = [locations: Location]


}

class ProductLocation {

    Product product
    Location location


    static mapping = {
        version false
    }

    static constraints = {

    }

    static belongsTo = [products: Product, locations: Location]


}

class Location  {

    Company customer
    Location parent
    String name
    String description
    String objectnumber
    String address
    String zipcode
    String province
    String city
    String country
    Long longitude
    Long latitude
    Integer order
    String timezone
    AlertConfiguration alertConfiguration
    boolean deleted
    LocationType type


    static hasMany = [products: Product]

    static mapping = {

    }


}

标签: hibernategroovy

解决方案


尝试以下操作:

List<Product> findByLocation(Location location){
    ProductLocation.createCriteria().list {
        eq('location', location)
        projections {
            property( 'product' )
        }
    }
}

推荐阅读