#java #spring #spring-boot
#java #весна #spring-загрузка
Вопрос:
Я использую Spring Data и хочу получать данные, отсортированные по идентификатору из базы данных.Когда я пишу findAllByOrderById, произошла ошибка.Я думаю, что код ошибки «Не найден идентификатор свойства для типа Employee!» Но я не знаю, где исправить. Репозиторий
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
public List<Employee> findAllByOrderById();
}
Модель
@Table(name = "employees")
@Entity
@Getter
@Setter
public class Employee {
@Id
@Column(name = "emp_id", length = 8)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer emp_id;
@Column(name = "emp_code", length = 20, nullable = false)
private String emp_code;
@Column(name = "emp_name", length = 20, nullable = false)
private String emp_name;
}
Контроллер
@Controller
public class DemoController {
@Autowired
EmployeeRepository empRepository;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
List<Employee> emplist = empRepository.getAllEmployeesOrderById();
model.addAttribute("emplist", emplist);
return "view/index";
}
}
Вид
<body>
<div id="wrapper">
<div id="header">
<h1>日報管理システム</h1>
</div>
<div id="parent" th:include="app"></div>
</div>
<h1 th:text="${title}"></h1>
<table>
<tr th:each="emp : ${emplist}" th:object="${emp}">
<td th:text="*{emp_id}"></td>
<td th:text="*{emp_name}"></td>
</tr>
</table>
<br>
</body>
Код ошибки
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List spring.repositries.EmployeeRepository.findAllByOrderById()! No property id found for type Employee!
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List spring.repositries.EmployeeRepository.findAllByOrderById()! No property id found for type Employee!
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property id found for type Employee!
Ответ №1:
Вероятно, имя, которое вы должны использовать для метода, должно быть:
findAllByOrderByEmp_IdAsc()
или
findAllByOrderByEmp_IdDesc()
в зависимости от ваших потребностей.
Полные документы для именования метода создания запроса здесь
В качестве рекомендации также в Java обычно используется именование полей — camelCase .
Так, например, если ваше поле будет названо empId
, ваш метод будет назван findAllByOrderByEmpIdAsc()
Комментарии:
1. Извините, я могу получить данные, но данные не отсортированы. Это еще одна проблема?
2. Да, возможно, вам придется добавить «Asc» или «Desc» в конце