我有一个表,其中包含它指向的实体的条形码的字符串值。不幸的是,它不是外键,它只是一个字符串,所以不存在映射。这使得连接操作变得困难。我想知道如何将这个对象加入到另一个没有定义关系的表中。例如:
@Entity
@Table(name = "TblSample", schema = SCHEMA, catalog = CATALOG)
public class Sample {
@Id
@Column(name = "id", nullable = false)
private int id;
@Column(name = "barcodeEntity", nullable = false)
private String barcodeEntity;
@OneToOne
@JoinColumn(name = "barcodeContainer", nullable = false)
private Container container;
...
}
@Entity
@Table(name = "TblSoil", schema = SCHEMA, catalog = CATALOG)
public class Soil {
@Column(name = "barcode", nullable = false)
private String barcode;
@Column(name = "name", nullable = false)
private String name;
...
}
@Entity
@Table(name = "TblLeaf", schema = SCHEMA, catalog = CATALOG)
public class Leaf {
@Column(name = "barcode", nullable = false)
private String barcode;
@Column(name = "name", nullable = false)
private String name;
...
}
@Entity
@Table(name = "TblContainer", schema = SCHEMA, catalog = CATALOG)
public class Container {
@Column(name = "barcode", nullable = false)
private String barcode;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "location", nullable = false)
private String location;
...
}
因此,我想使用 CriteriaQuery 可以返回所有样本并加入从中获取的实体。我已经开始写它,但是当我试图弄清楚如何去做时,我被卡住了。在 sql 中它会像这样:
SELECT TOP 100
sample.Id
, sample.barcodeEntity
, leaf.name
, soil.name
, sample.barcodeContainer
, container.name
, container.location
FROM TblSample sample
LEFT JOIN TblSoil leaf on
soil.barcode = sample.barcodeEntity
LEFT JOIN TblLeaf leaf on
leaf.barcode = sample.barcodeEntity
JOIN TblContainer container on
container.barcode = sample.barcodeContainer
我猜想关联的 jpa CriteriaQuery 看起来像这样:
public void findSamples(Map<String, String> filterCriteria) {
final CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
final CriteriaQuery<SampleLocation> query = builder.createQuery(SampleLocation.class);
final Root<Sample> derivation = query.from(Sample.class);
// Note that the next two lines don't work
final Join<Leaf> joinOnLeaf = derivation.join(Sample_.barcodeEntity, JoinType.LEFT);
final Join<Soil> joinOnSoil = derivation.join(Sample_.barcodeEntity, JoinType.LEFT);
final Join<Container> joinOnContainer = derivation.join(Sample_.barcodeContainer);
CompoundSelection<SampleLocation> cSelect =
builder.construct(SampleLocation.class, sample.Id, sample.entitybarcode, joinOnLeaf.get(Leaf_.name), joinOnLeaf.get(Soil_.name), sample.barcodeContainer, joinOnContainer.get(Container_.name), joinOnContainer.get(Container_.location));
query.select(cSelect);
TypedQuery<SampleLocation> typedQuery = entityManager.createQuery(query);
typedQuery.setMaxResults(100);
return typedQuery.getResults();
}
有什么想法可以执行左连接操作吗?我无法根据 CriteriaQuery api 弄清楚如何做到这一点。似乎应该存在的东西。