【问题标题】:Retrieve primary key from table with HQL使用 HQL 从表中检索主键
【发布时间】:2012-04-18 14:26:24
【问题描述】:

我有一张桌子是 | 客户 ID |客户姓名 |客户国家|。

如何编写 HQL 查询来检索与 CustomerName 和 CustomerCountry 的组合对应的 CustomerId?

这是我的 CustomerDaoImpl:

@Repository
public class CustomerDaoImpl implements CustomerDao {

@Autowired(required=true)
private SessionFactory sessionFactory;

public Customer getCTID(String customerName, String customerCountry) {
    return (Customer) 
this.sessionFactory.getCurrentSession().createQuery(/* Some query that gets CTID corresponding to customerName and customerCountry*/);

}
}

我想使用此 CustomerId 并将其插入到我的 DeliveryTable 中以进行新的交付。我将 DTO 用于输入交付信息的表单,并且我将使用 DeliveryService 创建新交付,该交付使用 CustomerService 通过 CusomerDAO 检索 CustomerId。

感谢您的帮助, D

【问题讨论】:

标签: java database spring hibernate hql


【解决方案1】:

这是 Nitin 使用命名参数的答案,正如 JB Nizet 指出的那样:

Long id = this.sessionFactory.getCurrentSession().createQuery(
   "select customerId from Customer where customerName = :name and customerCountry = :country")
   .setParameter("name", customerName).setParameter("country", customerCountry).uniqueResult();

【讨论】:

    【解决方案2】:

    据我了解,与 Customer:Delivery 存在 1:N 关系。如果您使用多对一映射而不是直接使用 ID,这将是有益的。

    如果你仍然想要 HQL,你可以使用

    this.sessionFactory.getCurrentSession().createQuery(
        "from Customer customer where customer.customerName = :name "
        + " and customer.customerCountry = :country").setParameter("name",customerName).setParameter("country",countryName).uniqueResult();
    

    uniqueResult 因为我假设 customerName + Country 在数据库中是唯一的。如果不是,您需要使用.setMaxResult(1),否则从ListCustomer 的映射会出错。

    【讨论】:

    • 谢谢!我使用多对一映射映射表,但由于我希望用户不必知道 CustomerId,因此我创建了一个包含 Product、CustomerName、CustomerCountry 和 Date 的 DTO。我要做的是使用客户名称和国家/地区来获取 customerId(它们都已经存在于数据库中),以便我可以将 customerId 插入到我的交付表中以进行新的交付。 (希望这很清楚)您对关系的假设是正确的:)
    • -1 用于使用连接而不是(命名的)查询参数。这为 HQL 注入攻击打开了大门,并且会导致无效的 HQL,例如,customerName id O'Reilly..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多