简体   繁体   中英

Using Java constructors with Hibernate queries

I have a database that holds a certain type of object, we'll call it BaseObject. My project also has two other objects that share many fields with the BaseObject, that have more specific uses. I'd like the dao to have three functions, that call three hibernate queries, getAllBaseObjects, getAllObjectOnes, and getAllObjectTwos. The queries I'm currently using look like this:

<query name="getAllBaseObjects">
    from com.example.BaseObject
</query>
<query name="getAllObjectOnes">
    select new com.example.ObjectOne(parameter1, parameter2)
    from com.example.BaseObject
</query>
<query name="getAllObjectTwos">
    select new com.example.ObjectTwo(parameter1, parameter2, parameter3)
    from com.example.BaseObject
</query>

where parameter1, parameter2, etc are fields in the BaseObject and constructor parameters in the other two objects. However, both of the objects also have constructors that take an instance of the BaseObject, and I was wondering if there is any simple way to use that constructor in the hibernate queries. I've tried

<query name="getAllObjectOnes">
    select new com.example.ObjectOne(*) 
    from com.example.BaseObject
</query>

and

<query name="getAllObjectOnes">
    select new com.example.ObjectOne(com.example.BaseObject) 
    from com.example.BaseObject
</query>

but neither of them seemed to work.

Is there a way to do what I want, or will I have to just keep what I currently have?

Try to use the entity alias like:

<query name="getAllObjectOnes">
    select new com.example.ObjectOne(b) 
    from com.example.BaseObject b
</query>

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