简体   繁体   English

基于用户搜索的java动态where子句

[英]java Dynamic where clause based on user search

Hi i need to dynamically build a query based on user selection. 嗨,我需要根据用户选择动态构建查询。 I cant write where conditions with if statement because i have 50 columns in table.is there a way without if statements? 我不能用if语句写条件条件,因为我在table。中有50列。有没有if语句的方法吗?

You can look on CrtitriaAPI or you can use hibernate feature Query by example 您可以查看CrtitriaAPI或通过示例使用休眠功能查询

Actually if you are using spring with spring data module you can look into Specifications 实际上,如果您使用带有弹簧数据模块的弹簧,则可以查看规格

Please look into below links: 请查看以下链接:

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/ 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-specification-and-querydsl /

Do you mean how to avoid the sql injection like concatenating sql statements at runtime? 您的意思是如何避免在运行时连接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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM