hibernate - Hibernate 搜索:在复合键 EmbeddedId 中搜索
问题描述
我将类CKey
定义为嵌入式 id 类。
我定义了类BEntity
并为复合主键使用了双向字符串字段桥。
我AEntity
用与 的关系ManyToOne
来定义类BEntity
。
@Entity @Indexed
public class AEntity {
@ManyToOne(optional = false) @IndexedEmbedded(depth = 1, includeEmbeddedObjectId = true)
@JoinColumns(value = { @JoinColumn(name = "fk_fId", referencedColumnName = "fId"),
@JoinColumn(name = "fk_sId", referencedColumnName = "sId") }, foreignKey = @ForeignKey(name = "fk_sub"))
private BEntity bEntity;
}
@Entity @Indexed
public class BEntity {
@EmbeddedId @IndexedEmbedded @FieldBridge(impl = CompositeIdBridge.class)
private CKey cKey;
}
@Embeddable @Indexed
public class CKey {
@Field
private String fId;
@Field
private String sId;
}
public class CompositeIdBridge implements TwoWayStringBridge {
@Override
public String objectToString(Object object) {
return String.format("%s.%s", (CKey) object.getFId(), (CKey) object.getSId());
}
@Override
public Object stringToObject(String stringValue) {
String[] compositeIdProperties = stringValue.split("\\.");
return new CKey(compositeIdProperties[1], compositeIdProperties[2]);
}
}
然后,我尝试对 Entity 类进行休眠搜索AEntity
,但遇到了这个异常:
无法在 AEntity 中找到字段 bEntity.cKey.fId
Query query = getQuery().bool()
.must(getQuery().keyword().onField("bEntity.cKey.fId").matching("111111").createQuery())
.must(getQuery().keyword().onField("bEntity.cKey.sId").matching("222222").createQuery()).createQuery();
FullTextQuery fullTextQuery = getFullTextEntityManager().createFullTextQuery(query, AEntity.class);
解决方案
您@IndexedEmbedded(depth = 1)
的 inAEntity
明确要求仅嵌入深度为 1 的字段。bEntity.cKey
相对于 位于深度 1 bEntity
,但bEntity.cKey.fId
和bEntity.cKey.sId
位于深度 2。
要么你应该增加深度:
@Entity @Indexed
public class AEntity {
@ManyToOne(optional = false)
@IndexedEmbedded(depth = 2, includeEmbeddedObjectId = true)
@JoinColumns(value = { @JoinColumn(name = "fk_fId", referencedColumnName = "fId"),
@JoinColumn(name = "fk_sId", referencedColumnName = "sId") }, foreignKey = @ForeignKey(name = "fk_sub"))
private BEntity bEntity;
}
...或者您应该明确包括这些字段:
@Entity @Indexed
public class AEntity {
@ManyToOne(optional = false)
@IndexedEmbedded(depth = 1, includeEmbeddedObjectId = true,
includePaths = {"cKey.fId", "cKey.sId"})
@JoinColumns(value = { @JoinColumn(name = "fk_fId", referencedColumnName = "fId"),
@JoinColumn(name = "fk_sId", referencedColumnName = "sId") }, foreignKey = @ForeignKey(name = "fk_sub"))
private BEntity bEntity;
}
推荐阅读
- java - 如果某些字段具有集合类型,如何覆盖等于和哈希码?
- mysql - 将 UTF-8 字符串从 SAS 写入 MySQL
- python - hackerank 显示此消息: ~ 标准输出无响应 ~ 和 ValueError: invalid literal for int() with base 10: '2 3 6 6 5'
- asp.net - Asp.Net 如何获取正则表达式的字符串结果而不仅仅是一个
- excel - 为数千个单元格添加后缀 VBA
- swift - 检查用户是否登录了firebase
- c++ - noexcept 说明符取决于模板类成员函数
- json - Powerapps 中的嵌套表 - 解析 JSON 时删除“值”列
- java - 为什么 Kotlin 进行空检查,当反编译为 Java 时会声明一些未使用的变量?
- java - ElGamal 阈值加密 - 非确定性解密问题