简体   繁体   中英

JPQL one-to-many query

Entity A has a collection of some entities of type B. Type B is not aware (and should not be) of what type A is. I'd like to query for A which has at least one B with certain property.

As for the mappings I use simple one-to-many and a join-column inside it at the A mapping side.

Yet, when I do this using JPQL I cannot really use the JPA-generated column a_id since it's not a field of B - and therefore results in PropetyNotFound - jpa exception. Is there a method to use that column not having to define a property in the entity itself?

Entity A mapping:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm 
        http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
    version="2.0">

    <package>com.example</package>

    <entity class="B" access="FIELD">
        <attributes>
            <id name="seqid">
                <generated-value strategy="AUTO" />
            </id>
            <basic name="identifier" />
            <basic name="payload" />
            <version name="version" />
        </attributes>
    </entity>

    <entity class="A" access="FIELD">
        <attributes>
            <id name="seqid">
                <generated-value strategy="AUTO" />
            </id>
            <one-to-many name="bset">
                <join-column name="a_id"
                    referenced-column-name="seqid" />
                <cascade>
                    <cascade-all />
                </cascade>
            </one-to-many>
        </attributes>
    </entity>

</entity-mappings>

Thanks!

Just make sure you're using join clause on the set. Without it query will be constructed with no errors but this will fail with a strange error when executed. So the correct query would look like

select a from A a join a.setB b where b in (select c from B where B.x = 'x');

this will be successful but

select a from A a where a.setB in (select c from B where B.x = 'x');

will fail with no apparent reason.

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