Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 949697
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T23:26:32+00:00 2026-05-15T23:26:32+00:00

I have a query with a self join that looks like this, select t1.

  • 0

I have a query with a self join that looks like this,

select t1., t2. from table t1
left outer join table t2 on t2.LFT < t1.LFT
and t2.RGT > t1.RGT
AND t2.REG_CODE_PAR = ‘ALL’
AND t1.STATUS_CODE = ‘A’
AND t2.STATUS_CODE = ‘A’

I’m using @NamedNativeQuery with a result set mapping to get the result.

@NamedNativeQuery(
    name="findTree",
    query="..... the query above", 
    resultSetMapping = "regionT")

With the following result set mapping

@SqlResultSetMapping(name = "regionT" , entities ={
    @EntityResult( 
        entityClass = Tree.class
        fields = {
            @FieldResult(name = "regCode", column = "REG_CODE")
            @FieldResult(name = "rgt", column = "RGT"),
            @FieldResult(name = "lft", column = "LFT"),
            @FieldResult(name = "name", column = "NAME"),
            @FieldResult(name = "regCodePar", column = "REG_CODE_PAR"),
            @FieldResult(name = "statusCode", column = "STATUS_CODE")
        }
    ),
    @EntityResult(
        entityClass = TreeSelf.class
        fields = {
            @FieldResult(name = "regCode1", column = "REG_CODE")
            @FieldResult(name = "rgt1", column = "RGT"),
            @FieldResult(name = "lft1", column = "LFT"),
            @FieldResult(name = "name1", column = "NAME"),
            @FieldResult(name = "regCodePar1", column = "REG_CODE_PAR"),
            @FieldResult(name = "statusCode1", column = "STATUS_CODE")
        }
    )
})

The entity class contains looks like this.

@NamedNativeQuery(...)
@SqlResultSetMapping(...)
@Entity
@Table(name = "table")
public class Tree implements Serializable {

    @Id
    @Column(name = "REG_CODE")
    private String regCode;  ... ..getters and setters...}

When I run the query using em.createQuery(“findTree”), I get the exact same object in both

the 1st and 2nd elements of the returned object array.
Even if I create a class called TreeSelf that is identical to Tree and use it as the 2nd

EntityResult instead of having 2 EntityResults using the same entityClass, I get the same

result.

Can someone point out what’s wrong with the configuration?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T23:26:33+00:00Added an answer on May 15, 2026 at 11:26 pm

    Let’s see if I understand your question. You’re expecting to capture two Tree entities from each native query result row. The first entity should be formed from t1‘s columns. The second entity should be formed from t2‘s columns. Contrary to expectation, you actually receive two instances formed from t1. No instances from t2 appear. You made a doppelganger Entity for Tree called TreeSelf while debugging, but TreeSelf is ultimately unnecessary and you want to get rid of it. Stop me if any of that was wrong.

    I think the problem is due to ambiguous column names. Each column name in the native query appears twice, once from t1 and once from t2. The result mapper seems to be arbitrarily picking the first occurrence of each ambiguous column name for both Tree entities. I’m surprised that works at all. I would have expected an SQLException complaining about column reference ambiguity.

    Also, are you sure you want a left outer join? What if no match is found for a t1 row? It will be paired with all NULL in t2‘s columns. Then you have a null-valued Tree entity. I think. I don’t even know what the result mapper would do in that case. Perhaps you want an inner join?

    Consider translating this native query into a JPQL query. (JPA Criteria API is just as well, but I find it more cumbersome for examples.) Here’s a JPQL version of the native query:

    SELECT t1, t2 
    FROM Tree t1, Tree t2
    WHERE t2.lft < t1.lft AND t2.rgt > t1.rgt AND t2.regCodePar = 'ALL' AND
          t1.statusCode = 'A' AND t2.statusCode = 'A'
    

    N.B.: This changes the join semantics to inner instead of left outer.

    Here’s a sketch of code that could run this query:

    EntityManager em = ... // EntityManager by injection, EntityManagerFactory, etc.
    String jpql      = ... // Like example above
    TypedQuery<Object[]> q = em.createQuery(jpql, Object[].class);
    
    for (Object[] oa : q.getResultList()) {
       Tree t1 = (Tree)oa[0];
       Tree t2 = (Tree)oa[1];
    }
    

    In case you are stuck with the native query for whatever reason, here’s how you can work around the column name ambiguity. Instead of starting the native query like select t1.*, t2.*, alias each column with AS. The SELECT clause would resemble this:

    SELECT t1.REG_CODE AS t1_REG_CODE, t1.RGT AS t1_RGT, (... rest of t1 cols ...), 
           t2.REG_CODE AS t2_REG_CODE, t2.RGT AS t2_RGT, (... rest of t2 cols ...)
    

    The column attribute in each FieldResult must change accordingly. So the column attributes under the first EntityResult should all start with t1_ and the second’s should all start with t2_.

    I’d humbly recommend deleting the native query and sql result mapper and using JPA Query Language or Criteria API, if you can find a way.

    Update: As confirmed in your comments, a useful answer to your question must preserve left (outer) join semantics. Unfortunately, JPQL and the Criteria API don’t support complex left join conditions. There is no way to qualify a JPQL left join with an explicit ON condition.

    To my knowledege, the only way to do a left outer join under the spec is by traversing an entity relationship. The JPA implementation then generates an ON condition that tests identity equality. The relevant spec bits are 4.4.5 “Joins” and 4.4.5.2 “Left Outer Joins”.

    To satisfy this constraint, each Tree you want to left-join to its ultimate parent must have an additional column storing the ultimate parent’s id. You might be able to cheat around this constraint in a variety of ways (views?). But the path of least resistance seems to be modifying the native query to use aliased arguments, deleting TreeSelf, and updating the result mapper accordingly. Cleverer solutions welcome, though…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have query like this : SELECT EXTRACT(MONTH FROM d.mydate) AS synmonth, SUM(apcp) AS
I have built this query that is kind of self explanatory: SELECT events.*,(SELECT COUNT(*)
I have a table which I do a self-join. My sample table looks like
I have query to show the table like this: but I want to PIVOT
I have a table of node likes, which looks roughly like this: lid nid
i'm using cursor to loop through a self join table. the query that i
I'm doing a self join and I have the following query: select max( wf1.id
I have an SQL query that selects from two inner joined tables. The select
in my self-defined module I have this method which will query the db and
I have two tables that look like this: Supplier SN SNAME Stat City +----------+-------+----+--------+

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.