简体   繁体   中英

Grails: how to return instance of domain class when using projections

I have a domain class which has around 20 properties. A findBy on the domain class results in a select query which has all the columns selected from the database, which can be a performance hit when the required column could be only 1.

So I thought of using, withCriteria.

def sampleDomainInst = SampleDomain.withCriteria{
    projections {
        property('fieldOne')
       }
     eq('id', idVal)
  } 

The value returned is a list. But what I need is an instance of SampleDomain How do I do that?

Thank You. Regards, Jay Chandran

The goal of projections is IMHO not to have domain instances returned. In theory you might add 'id' to the projections closure and then you can do a DomainClass.get(id). But that is the same as working completely without the projection.

If your domain class has so many properties that a you're using projections to get only parts of them, you should consider splitting up the domain class in multiple joined classes. A good design practice is that each class should only represent one single abstraction.

Try withCriteria(uniqueResult: true) {...} or, longer, SampleDomain.createCriteria().get {...} .

OTOH, how can you select only 1 column, if you're selecting whole SampleDomain object (unless most of its properties are lazily-fetched)? That sounds unclear.

// And I believe you'll get more performance hits then selecting 20 fields for 1 record.

def whatYouWant = sampleDomainInst[0] 

除非我错过了什么。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM