【问题标题】:ResultTransformer with createSQLQuery forces no camelCase in entity fields带有 createSQLQuery 的 ResultTransformer 在实体字段中强制没有驼峰式
【发布时间】:2011-12-29 11:45:55
【问题描述】:

我有一个sql查询如下:

List<Employee> employees = getCurrentSession()
                    .createSQLQuery(
                            "select"
                                    + e.id as id,e.first_name as firstName,e.password as password
                                    + "from employee e,employee_role er,role r where e.employee_id=er.employee_id and er.role_id=r.role_id and r.name='ROLE_ADMIN' ")
                    .setResultTransformer(Transformers.aliasToBean(Employee.class))
                    .list();

我在 Employee 中有一个名为 firstName 的属性,但是在单元测试中尝试在 dao 之上运行时,我收到以下异常:

org.hibernate.PropertyNotFoundException: Could not find setter for firstname on class com.app.domain.Employee

我不知道 hibernate 从这个 firstname 属性中得到什么?我的查询没有正确?

解决方法是将属性更改为名字,以及getter,setter 但是任何想法为什么hibernate会做出这种行为,以及如何避免它,因为我想在我的域中使用camelCase,请告知。

【问题讨论】:

    标签: hibernate postgresql


    【解决方案1】:

    这可能与您如何(以及是否)配置您的NamingStrategy有关

    http://matthew.mceachen.us/blog/hibernate-naming-strategies-20.html

    或

    如果您使用 MySQL 来判断天气,您是否已启用区分大小写的表/列名称 http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html

    【讨论】:

      【解决方案2】:

      对于更简单的解决方案,请在发送到服务器的查询中用双引号引起来。而不是

      e.first_name as firstName
      

      它应该是

      e.first_name as "firstName"
      

      在 PostgreSQL 中,双引号会强制区分大小写。不加引号,它(大部分)遵循 SQL 标准并折叠成单个大小写(尽管标准是大写的小写)。

      【讨论】:

        【解决方案3】:

        您可以使用addScalar(String columnAlias, Type type) 显式声明您的原生SQL 的列别名:

          getCurrentSession()
          .createSQLQuery( "select e.id as id,e.first_name as firstName,e.password as password from xxxxxx")
                        .addScalar("id",StandardBasicTypes.INTEGER )
                        .addScalar("firstName",StandardBasicTypes.STRING )
                        .addScalar("password",StandardBasicTypes.STRING )
                        .setResultTransformer(Transformers.aliasToBean(Employee.class))
                        .list();
        

        【讨论】:

        • addScalar+select as in the query ?
        • 我认为是这样,因为只使用 addScalar() 而不使用 select as 会给我错误。
        猜你喜欢
        • 2016-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-04
        • 2013-09-29
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        相关资源
        最近更新 更多