'Java Mybatis to Python SQL Alchemy - is there resultMap mybatis equivalent in SQLAlchemy python. which logically maps join queries removing duplicates

Say we have a select query like

select a.col1,a.col2,a.col3,b.col1,b,col2,c.col1
from a, b, c
where a.col1(+)=b.col2 and b.col3(+)=c.col2

In mybatis xml we have mapper defined which could include associations and collection result mapped to Mybatis "resultMap". Mybatis maps respective columns from SQL query to result objects without duplication of objects when we use "resultMap"

Is there something similar in SQLAlchemy?

<resultMap id="example" type="ExampleClass1">
  <id property="attribute1" column = "a.col1"/>
  <result property="attribute2" column = "a.col2"/>
  <result property="attribute3" column = "a.col2"/>
  <association property = "assocattribute" javaType="ExampleClass2" 
             resultMap = "assocMap">
  <collection property = "listattribute" "ofType" = "ExampleClass3" 
               resultMap = "collectMap">
</resultMap>
            
<resultMap id="assocMap">
  <result property = "assocattribute1" column = "b.col1">
  <result property = "assocattribute2" column = "b.col2">
</resultMap>
            
<resultMap id="collectMap">
  <result poperty = "collectattribute1" column = "c.col1">
</resultMap>          

In the above example. joins are handled and duplicates are removed by mybatis. similar solution is needed in sqlalchemy if possible.

|a.col1 |a.col2|a.col3|b.col1|b.col2|c.col1|
|-------|------|------|------|------|------|
| a     | b    |   c  |d     |e     |f     |
| a     | b    |   c  |d     |e     |g     |
| a     | b    |   c  |d     |e     |j     |
| a     | b    |   c  |d     |e     |k     |

     

required java object is Abstract representation

ExampleClass1 {
   attribute1:a,
   attribute2:b,
   attribute3:c,
   assocattribute=> ExampleClass2 {
                assocattribute1:d,
                assocattribute2:e
              }
   collectattribute=> List( ExampleClass3{collectattribute1:f }
                             ,ExampleClass3{collectattribute1:g }
                              ,ExampleClass3{collectattribute1:J }
                              ,ExampleClass3{collectattribute1:K }
}

We tried few things like sqlalchemysession.query(a,b,c).join() with conditions etc.. where objects from a, b, c are duplicated on join conditions. But in Mybatis "resultMap" removes duplicates and maps to proper output object.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source