带有 createSQLQuery 的 ResultTransformer 强制实体字段中不使用驼峰式命名法

问题描述 投票:0回答:3

我有一个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 从这个名字属性中获取什么?我在查询中没有纠正它?

解决方法是将属性更改为名字,以及 getters、setters 但如果有任何关于 hibernate 为何会产生这种行为以及如何避免这种行为的想法,因为我想在我的域中使用驼峰命名法,请告知。

hibernate postgresql
3个回答
26
投票

您可以使用 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();

20
投票

为了更简单的解决方案,请在发送到服务器的查询中对标识符加双引号。而不是

e.first_name as firstName

应该这样读

e.first_name as "firstName"

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


0
投票

这可能与您如何(以及是否)配置

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

© www.soinside.com 2019 - 2024. All rights reserved.