Can we concatenate two properties in Hibernate HQL query?

前端 未结 4 476
感动是毒
感动是毒 2020-12-10 01:31

Lets say I have one table with two columns firstname and lastname with String datatype. Normally I write my hql query like

\"selec         


        
相关标签:
4条回答
  • 2020-12-10 01:41

    I did it so with hql

    public List<Contract> findContracts(String fullName) {
        Query q = sessionFactory.getCurrentSession().createQuery("from Contract c where :fullName = concat(c.firstname, ' ', c.lastname)");
         q.setString("fullName", fullName);
         return q.list();}
    
    0 讨论(0)
  • 2020-12-10 01:43
    select concat(c.firstname, c.lastname) as fullname from Contact c
    

    or, if you want a separator:

    select concat(c.firstname, ' ', c.lastname) as fullname from Contact c
    

    See the documentation.

    0 讨论(0)
  • 2020-12-10 01:47

    You may create a calculated column in your entity:

    @Formula(value = " concat(first_name, ' ', last_name) ")
    private String fullName;
    

    And in your HQL you just refer to this field as you would do to any other.

    In your case, you can do:

    "select fullName from Contact"
    
    0 讨论(0)
  • 2020-12-10 01:49

    You can also use || concatenation operator:

    "select c.firstName || ' ' || c.lastName as fullName from Contact"
    

    allthough it may be confusing to read.

    0 讨论(0)
提交回复
热议问题