简体   繁体   English

如何使用 JPA EntityManager select 包括外部实体的多个列

[英]How to select multiple columns including the foreign entity using JPA EntityManager

I am trying to select multiple columns from 2 tables with OneToOne relationship, where the users will send the columns they want to search and the sever returns the result list contains only those columns.我正在尝试 select 具有 OneToOne 关系的 2 个表中的多个列,其中用户将发送他们想要搜索的列,并且服务器返回的结果列表仅包含这些列。 I have two entities like these:我有两个这样的实体:

@Table(name = "user")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;

    @Column(name = "id" )
    @Id
    private String id;

    private String name;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonManagedReference
    private Address address;

    //Getters and Setters
}
public class Address  implements Serializable{
    private static final long serialVersionUID = 1L;
    
    @Column(name = "user_id" )
    @Id
    private String id;

    private String houseNr;
    
    @OneToOne
    @JoinColumn(name = "user_id")
    @JsonBackReference
    private Networkdata networkdata;
    
    //Getters and Setters

With search functions using EntityManager with Tuple使用 EntityManager 和 Tuple 的搜索功能

public List<?> find(String[] neededFields){
   if(neededFields.length > 0){
      String queryStr = this.createQueryString(neededFields);

      TypedQuery<Tuple> query = em.createQuery(queryStr, Tuple.class);

      List<Map<String, Object>> resultList = new ArrayList<>();
        
      query.getResultList().forEach(tuple -> {
         Map<String, Object> map = new HashMap<>();
         List<TupleElement<?>> elements = tuple.getElements();
         for (TupleElement<?> element : elements ) {
            String alias = element.getAlias();
                    
            map.put(alias, tuple.get(alias));
         }
                
         resultList.add(map);
      });

      return resultList; 
   }
   else{
      return em.createQuery(this.FIND_ALL_STR, User.class).getResultList();
   }
}

When i search using SELECT u FROM User u, Address a WHERE u.id = a.id .当我使用SELECT u FROM User u, Address a WHERE u.id = a.id It returns result like this:它返回这样的结果:

[
   {
      "id": "5e4e3c95cd8b290008db6f3c",
      "name": "name",
      "address": {
         "id": "5e4e3c95cd8b290008db6f3c",
         "houseNr": "123ABC"
      }
   }
]

Another case is SELECT u.address as address FROM User u, Address a WHERE u.id = a.id which returns另一种情况是SELECT u.address as address FROM User u, Address a WHERE u.id = a.id返回

[
   {
      "address": {
         "id": "5e4e3c95cd8b290008db6f3c",
         "houseNr": "123ABC"
      }
   }
]

But when i add a little spicy ingredient like for example, to select the id and the whole address entity like this SELECT u.id as id, u.address as address FROM User u, Address a WHERE u.id = a.id it returns但是,当我添加一点辛辣成分时,例如,向 select 中添加 id 和整个地址实体,例如SELECT u.id as id, u.address as address FROM User u, Address a WHERE u.id = a.id返回

[
   {
      "id": "5e4e3c95cd8b290008db6f3c",
      "address": null
   }
]

Why the first two queries are perfectly fine but the last just returns a null address?为什么前两个查询非常好,但最后一个只返回null地址? How can i solve this?我该如何解决这个问题?

Other ideas are also welcome.也欢迎其他想法。

If you searching from two column, you can actually use INNER JOIN key words with FOREIGN KEY on the Adress.如果您从两列搜索,您实际上可以在地址上使用 INNER JOIN 关键字和 FOREIGN KEY。 If you still want to trim down your search you can always use WHERE clause.如果您仍然想减少搜索,您可以随时使用 WHERE 子句。 SELECT u.id as Id, a.address as Adress from User u INNER JOIN Address a ON u.id=a.user.id. SELECT u.id 作为 Id,a.address 作为来自用户 u INNER JOIN 的地址 a ON u.id=a.user.id。 to trim down your search you can add “WHERE u LIKE %?1% AND a LIKE %?1% ORDER BY u.id “要减少您的搜索,您可以添加“WHERE u LIKE %?1% AND A LIKE %?1% ORDER BY u.id”

Better still to save yourself from headache you can use RESPONSE CLASS to map out the column you want to search from something like SELECT new UserAddress(u.id, a.address)......最好还是让自己免于头痛,您可以使用 RESPONSE CLASS 到 map 从您想要搜索的列中删除,例如 SELECT 新用户地址(u.id,a。

I hope I'm able to help.我希望我能提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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