大家好, 我想知道使用 Spring Data Jpa 的 custum 查询有什么问题。 如果我使用
UtilisateurRepositorie.findAll()
,工作正常
我的存储库:
@Repository
public interface UtilisateurRepositorie extends JpaRepository <Utilisateur, Long> {
@Query ("select u.idUtilisateur, u.login, u.mail, u.nom, u.prenom,u.poste.nomposte, u.idChantier.nomChantier from Utilisateur u ")
List<Utilisateur> selectAllUser();
}
在我的 Controller 中
@Autowired
private UtilisateurRepositorie utilisateurRepositorie;
@GetMapping("/userlist")
public String listerUtilisateur(@RequestParam (name = "page", defaultValue = "0") int page , Model model) {
List<Utilisateur> lstUser= utilisateurRepositorie.selectAllUser();
model.addAttribute("listeusers", lstUser);
return "utilisateur";
}
我使用 thymeleaf 来表达我的观点:
<div>
<table class="table table-responsive table-bordered">
<thead>
<tr>
<th data-breakpoints="xs">Login</th>
<th>Nom</th>
<th>Prenom</th>
<th data-breakpoints="xs">mail</th>
<th data-breakpoints="xs">Poste</th>
<th data-breakpoints="xs">Chantier</th>
</tr>
</thead>
<tbody>
<tr th:each="listeuser:${listeusers}">
<td th:text="${listeuser.getLogin()}"></td>
<td th:text="${listeuser.nom}"></td>
<td th:text="${listeuser.prenom}"></td>
<td th:text="${listeuser.mail}"></td>
<td th:text="${listeuser.poste.nomposte}"></td>
<td th:text="${listeuser.idChantier.nomChantier}"></td>
</tr>
</tbody>
</table>
</div>
编译后,出现以下错误:
org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method getLogin() cannot be found on java.lang.Object[] type
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:211) ~[spring-expression-4.3.6.RELEASE.jar:4.3.6.RELEASE]...
谢谢
最佳答案
那是因为您正在尝试转换 List<Object[]>
至List<Utilisateur>
.
当您执行此类查询时
@Query ("select u.idUtilisateur, u.login, u.mail, u.nom, u.prenom,u.poste.nomposte, u.idChantier.nomChantier from Utilisateur u ")
List<Utilisateur> selectAllUser();
它返回List<Object[]>
,因为您选择了多个字段。
您应该将查询重写为 select u from Utilisateur u
如果你想返回List<Utilisateur>
.
否则,需要解析Object[]
逐个元素。
关于java - spring-data-jpa 的查询注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49975580/