java对包含的实体执行类似查询
我有两张桌子;人和宠物
人
PERSON_ID PERSON_NAME FAVORITE_PET
1, Ryan, 1
宠物
PET_ID PET_NAME
1, Binky
一个人可能有也可能没有最喜欢的宠物
我想回报所有有一个像“宾基”这样名字的宠物的人
在SQL中,我将执行以下操作:-
SELECT *
FROM people people, pets pet
WHERE people.favorite_pet = pet.pet_id
AND pet.pet_name LIKE 'binky';
我已经将我的课程映射到下面:-
个人类
@Entity
@Table( name = "people" )
public class Person implements Serializable {
@Id @Column( name = "person_id" ) private long personId;
@Column( name = "person_name" ) private long personName;
@JoinColumn( name = "favorite_pet" ) @ManyToOne private Pet favoritePet;
}
宠物类
@Entity
@Table( name = "pets" )
public class Pet implements Serializable {
@Id @Column( name = "pet_id" ) private long petId;
@Column( name = "pet_name" ) private String petName;
}
要返回等效查询,我希望执行以下DetachedCriteria:-
DetachedCriteria criteria = DetachedCriteria.forClass( Person.class );
criteria.add( Restrictions.like( "favoritePet.petName", "binky" ) );
然而,当我这样做时,我得到以下错误:-
org.hibernate.QueryException: could not resolve property: favoritePet.petName of:
com.test.Person
使用限制进行此类查询的正确方法是什么
# 1 楼答案
我不知道为什么要使用Criteria API来进行这样一个简单的静态查询,而不是简单的HQL查询:
这将创建一个隐式内部联接,相当于
因此,如果你(真的)想通过条件查询实现这一点,你也需要一个joi: