Hibernate执行HQL报错无法找到profileJoinDto类匹配构造函数如何解决
错误原因
你遇到的HQL构造函数匹配错误,根本原因是在profileJoinDto类中没有定义与HQL查询参数数量、类型、顺序完全匹配的有参构造方法。
从栈追踪可以明确看到,Hibernate期望你提供一个接收6个String类型参数的profileJoinDto构造方法,但你当前的profileJoinDto只有Getter/Setter,没有对应的构造方法。
解决方法
方案1:新增匹配的有参构造方法
在profileJoinDto类中添加如下构造方法即可,注意参数顺序必须和HQL中SELECT new后面的字段顺序完全一致:
public profileJoinDto(String username, String email, String contact, String bio, String website, String gender) { this.username = username; this.email = email; this.contact = contact; this.bio = bio; this.website = website; this.gender = gender; }
如果后续需要查询u_id、p_id等更多字段,只需要在HQL的SELECT列表中添加对应字段,同时在构造方法中补充对应类型的参数即可。
方案2:改用接口投影(可选)
如果不想手动写构造方法,可以把profileJoinDto改成接口形式,只需要定义对应字段的getter方法即可,无需写new语法:
- 改
profileJoinDto为接口:
public interface profileJoinDto { String getUsername(); String getEmail(); String getContact(); String getBio(); String getWebsite(); String getGender(); }
- 修改HQL语句,去掉
new构造语法,保证字段别名和接口getter匹配:
@Query("SELECT r.username as username, r.email as email, r.contact as contact, p.bio as bio, p.website as website, p.gender as gender FROM profileEntity p JOIN p.registrationEntity r WHERE r.u_id = ?1") profileJoinDto findById(int id);
额外注意
Java类名建议遵循大驼峰命名规范,比如ProfileJoinDto、ProfileEntity、RegistrationEntity,符合通用开发规范的同时也能避免潜在的大小写匹配问题。
内容的提问来源于stack exchange,提问作者Faheem azaz Bhanej
相关产品推荐
相关产品推荐

