Stick on spring数据jpa left join提供多条具有相同数据的记录

uqdfh47h  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(311)

在运行springjpa的查询时,我得到了多个相同的条目
这是我的问题

  1. @Query(value = "Select * FROM t1" +
  2. " LEFT JOIN t2 im ON t1.id=im.id", nativeQuery = true)
  3. public List<GetList> getList()

当在mysql上运行时,这个查询给了我正确的数据,但是在springjpa上它给了我重复的记录t2有多个t1的记录id这里是sql的结果

  1. t2Id id
  2. 1 605
  3. 2 605
  4. 3 605
  5. 4 605
  6. 5 589
  7. 6 589
  8. 7 589
  9. 9 606
  10. 2
  11. 5
  12. 6
  13. 15
  14. 16
  15. 29

这是实体

  1. @Entity
  2. public class GetList {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. @Column(name = "id", unique = true, nullable = false)
  6. private Integer Id;
  7. @Column(name = "t2Id ", unique=true,nullable=false)
  8. private Integer t2Id ;
  9. }

这是springjpa的结果

  1. t2Id id
  2. 4 605
  3. 4 605
  4. 4 605
  5. 4 605

t2表数据和更多字段

  1. t2Id id
  2. 1 605
  3. 2 605
  4. 3 605
  5. 4 605
  6. 5 589
  7. 6 589
  8. 7 589
  9. 9 606
  10. 2
  11. 5
  12. 6
  13. 15
  14. 16
  15. 29

t1数据

  1. status id
  2. Active 605
  3. Active 589
  4. Active 606
  5. Active 2
  6. Active 5
  7. Active 6
  8. Active 15
  9. Active 16
  10. Active 29

我试过很多东西,但都没用。任何解决办法都会有帮助

8tntrjer

8tntrjer1#

根据您的评论,这是一个dto,而不是jpa的托管实体。放弃注解并为每个属性添加getter/setter。

  1. public class GetList {
  2. private int id;
  3. private int t2Id;
  4. public void setId(int id) { this.id=id;}
  5. public int getId() { return this.id;}
  6. public void setT2Id(int t2Id) { this.t2Id=t2Id;}
  7. public int getT2Id() { return this.t2Id;}
  8. public void hashCode() {
  9. return Objects.hashCode(this.id, this.t2Id);
  10. }
  11. public void equals(Object other) {
  12. if (other instanceof GetList) {
  13. GetList that = (GetList) other;
  14. return this.id == that.id && this.t2Id == that.t2Id;
  15. }
  16. return false;
  17. }
  18. }

springdatajpa现在将它用作投影,而不是托管实体。

展开查看全部

相关问题