【问题标题】:How to find by composite object property?如何通过复合对象属性查找?
【发布时间】:2016-09-19 07:04:11
【问题描述】:

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

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 org.hibernate.QueryException: could not resolve property: location.lName of: io.onek.entity.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;
}

【问题讨论】:

    标签: java hibernate spring-mvc


    【解决方案1】:

    您必须创建一个联接:

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

    但是对于这样一个简单的静态查询,我真的会避免使用 Criteria。使用 JPQL:

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

    【讨论】:

    • HQL——因为他使用了Session。而这个HQL 产生一个cross join
    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    相关资源
    最近更新 更多