简体   繁体   中英

hibernate createAlias with clause generates wrong query

I have the following tables: A: id B: id, text AB: aID, bID

I want to joib A and B where B.text contains the word 'cat'.

This is the hibernate query I do:

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. 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. You can fix it by using a restriction in the where clause

 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM