[英]hibernate createAlias with clause generates wrong query
I have the following tables: A: id B: id, text AB: aID, bID 我有以下表格:A:id B:id,文本AB:aID,bID
I want to joib A and B where B.text contains the word 'cat'. 我想joib A和B,其中B.text包含单词'cat'。
This is the hibernate query I do: 这是我做的hibernate查询:
Criteria c = session.createCriteria(TableA.class, "A");
c.createAlias("A.bs", "B", JoinType.INNER_JOIN, Restrictions.like("b.text", "%cat%"));
c.setProjection(Projections.property("id"));
The generated query is: 生成的查询是:
Select id
FROM A a
INNER JOIN AB ab ON a.id=ab.aID AND (b.text like ?)
INNER JOIN B b ON b.id=ab.bID AND (b.text like ?)
For some reason AND (b.text like ?)
appears in both inner joins. 出于某种原因AND (b.text like ?)
出现在两个内部联接中。 I far as I understand its supposed to be only in the second on. 据我所知,它应该只是在第二个。 This causes the following exception: 这会导致以下异常:
java.sql.SQLException: No value specified for parameter 2
I guess it's happening because it has only one parameters and two '?'. 我猜它正在发生,因为它只有一个参数和两个'?'。
What am I missing? 我错过了什么?
EDIT: 编辑:
Adding the persistent classes: 添加持久化类:
@Entity
@Table(name="A")
Class A {
@Id
@Column(name="id", length=255)
protected String id;
@OneToMany
@JoinTable(name="AB", joinColumns = @JoinColumn( name="aID"), inverseJoinColumns = @JoinColumn( name="bID"))
@LazyCollection(LazyCollectionOption.FALSE)
protected List<B> bs;
}
@Entity
@Table(name="B")
Class B {
@Id
@Column(name="id", length=255)
protected String id;
@Column(name="text", length=255)
protected String text;
}
I think you need to create an alias 我认为你需要创建一个别名
c.createAlias("A.bs", "b", JoinType.INNER_JOIN, Restrictions.like("b.text", "%cat%"));
Updated 更新
I think It is a Hibernate bug. 我认为这是一个Hibernate错误。 You can fix it by using a restriction in the where
clause 您可以通过在where
子句中使用限制来修复它
c.createAlias("A.bs", "b", JoinType.INNER_JOIN);
c.add(Restrictions.like("b.text", "%cat%"));
or don't use join table and do association by foreign key in B
. 或者不使用连接表并在B
中通过外键进行关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.