如何通过复合对象属性查找?

时间:2016-05-22 10:50:34

标签: java hibernate spring-mvc

我想找到城市名称与Madrin相等的所有计划(例如)。 但我总是得到一个错误。

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.hibernate.QueryException:无法解析属性:location.lName:io.onek.entity.FuturePlan。

帮助我搞清楚。

FuturePlan

@Entity
public class FuturePlan {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int fpId;
private String about;
@DateTimeFormat(pattern = "dd-mm-yyyy")
@Temporal(TemporalType.DATE)
private Date travelDate;
@ManyToOne(fetch=FetchType.EAGER)
private User user;
@ManyToOne(fetch=FetchType.EAGER)
private Location location;

public FuturePlan() {
    super();
}

public FuturePlan(String about, Date travelDate) {
    super();
    this.about = about;
    this.travelDate = travelDate;
}

public FuturePlan(String about, Date travelDate, User user, Location location) {
    this.about = about;
    this.travelDate = travelDate;
    this.user = user;
    this.location = location;
}
..get/set/

位置

@Entity
public class Location {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int lId;
private String lName;

public Location() {
    super();
}

public Location(int lId, String lName) {
    super();
    this.lId = lId;
    this.lName = lName;
}

来自我的DAOImpl的方法。

@Override
public List<FuturePlan> findByLocation(String name) {
    Session session = sessionFactory.openSession();
    Criteria cr = session.createCriteria(FuturePlan.class);
    cr.add(Restrictions.eq("location.lName", name));
    List<FuturePlan> list =  cr.list();
    session.close();
    return list;
}

1 个答案:

答案 0 :(得分:2)

您必须创建一个联接:

cr.createAlias("location", "l"));
cr.add(Restrictions.eq("l.lName", name));

但我真的会避免使用Criteria进行这样一个简单的静态查询。使用JPQL:

select fp from FuturePlan fp where fp.location.lName = :name