基于用户搜索的Java Dynamic where子句

时间:2018-11-11 18:36:06

标签: java jpa

嗨,我需要根据用户选择动态构建查询。我不能用if语句写条件,因为我在table中有50列。有没有if语句的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以查看CrtitriaAPI或使用休眠功能 通过示例查询

实际上,如果您使用带弹簧数据模块的弹簧,则可以查看规格

请查看以下链接:

https://dzone.com/articles/hibernate-query-example-qbe https://vladmihalcea.com/query-entity-type-jpa-criteria-api/ https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

答案 1 :(得分:0)

您是说如何避免像在运行时连接sql语句那样避免sql注入?

    static final String INVOICE_QUERY = "SELECT inv from Invoice inv WHERE (:createDate IS NULL OR inv.createDate = :createDate) AND (:quantity IS NULL OR inv.quantity = :quantity) AND (:custName IS NULL OR inv.custName = :custName)";
    Session session = getHibernateTemplate().getSessionFactory().openSession();

    Query query = session.createQuery(INVOICE_QUERY);
    query.setDate("createDate", createDate);
    if(quantity != null)
        query.setLong("quantity", quantity);
    else
        query.setBigInteger("quantity", null);
    if(StringUtils.isNotBlank(custName))
        query.setString("custName", custName);
    else
        query.setString("custName", null);
    return query.list();