sql - 来自 JPA 查询的重复数据(sql 约束)
问题描述
出于某种原因,我在存储库中使用此查询返回了 9 行重复数据。
@Query("select distinct profile from OfficeProfile profile where profile.fcoDesignCd in
(select officeLocation.asccode from OfficeLocation officeLocation, OfficeProfile profile
where officeLocation.statecode = :stateCode and officeLocation.asccode = profile.fcoDesignCd)")
public List<OfficeProfile> searchStateASC(@Param("stateCode") String stateCode);
下面是返回 9 个不同数据行的 sql 查询。查询似乎是相同的。
select
op.FCO_DESIGN_CD,
op.office_addr_line1,
op.office_addr_line2,
op.office_addr_state,
op.office_addr_zip
from cridba.office_profile op
where op.fco_design_cd in (
select asc_code from cridba.cris_lk_location cll , cridba.office_profile op
where cll.state_code='VA'
and cll.asc_code = op.fco_design_cd);
这就是我迭代这些值的方式。我设置了我的调试器,并注意到带有 id 的 9 个值。
for(OfficeProfile locationInfo: officeLocatorRepository.searchStateASC(stateCode))
这是我的实体关系。
办公室简介(父)
@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "profile")
private Set<OfficeLocation> officeLocation = new HashSet<>(0);
办公地点(儿童)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "asc_code", referencedColumnName = "fco_design_cd", nullable = false, insertable=false,
updatable=false)
public OfficeProfile profile;
我在两个类中都覆盖了equals和hashcode。因为我使用 asc_code 加入这些表,所以我会覆盖它还是 id?或两者?这是我到目前为止所拥有的。
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OfficeProfile officeProfile = (OfficeProfile) o;
if (officeProfile.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), officeProfile.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
即使这个表已经有一个ID,我是否应该将@Id 添加到fcoDesignCd?fcoDesignCd 是连接中的引用列吗?
@Column(name = "fco_design_cd")
private String fcoDesignCd;
HQL 输出...
select distinct officeprof0_.office_type_id as office_type_id1_1_, ......
from cridba.office_profile officeprof0_ where officeprof0_.fco_design_cd in
(select officeloca1_.asc_code
from cridba.cris_lk_location officeloca1_, cridba.office_profile
officeprof2_ where officeloca1_.state_code=? and
officeloca1_.asc_code=officeprof2_.fco_design_cd)
这看起来是正确的道路吗? JPA如何在@OneToMany关系的列上添加唯一约束,如用户名
解决方案
您不应该为您的表添加另一个 @Id 列,因为您已经有了一个。确保使用数据库中的唯一约束对其进行备份。
hashCode 和 equals 的覆盖看起来也不错。
重复的问题可能出在查询中。
推荐阅读
- javascript - 使用参数作为对象属性链的一部分
- javascript - PHP HTML CSS - 显示图像 1:1
- java - 为什么当我从 jaxws-maven-plugin 生成 wsdl 类时,由于缺少 ProviderImpl,它们无法在运行时运行?
- postgresql - Sequelize:返回单个 COUNT 条目而不是嵌套包含中的每一行
- logging - Mosquitto - 拥有主题客户端 IP 的日志
- oracle - 如何在 ubuntu 18.04 上设置 oracle 即时客户端?
- node.js - 如何在http方法级别的nestjs中创建@Version装饰器?
- ios - NVIDIA NVENC(媒体基金会)编码的 h.264 帧未使用 VideoToolbox 正确解码
- machine-learning - 具有不规则时间步长的时间序列作为机器学习回归工具的测试数据
- laravel - 添加 select2 插件以选择选项后。Laravel Livewire 搜索不起作用