所以,我的问题出在标题中 - crudrepository 方法 findAll()
返回一个空列表。我重写了 Crud 的方法,因为它返回了一个可迭代对象而不是一个列表。
我尝试使用 JpaRepository
而不是 CrudRepository
(当时我没有重写 findAll()
方法),但是得到了相同的结果。
我的代码:
事件.java
@Data
@Entity
@NoArgsConstructor
public class Event{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable=false)
private String name;
@Column(nullable=false)
private LocalDateTime time;
@ManyToOne
@JoinColumn
private City city;
}
城市.java
@Data
@Entity
@NoArgsConstructor
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable=false)
private Long code;
@Column(nullable=false)
private String name;
@OneToMany(mappedBy = "city", cascade = CascadeType.ALL)
private Set<Event> events;
}
CityRepository.java
@Repository
public interface CityRepository extends CrudRepository<City, Long> {
@Override
List<City> findAll();
}
EventsController.java
@Controller
@RequestMapping
public class EventsController {
@Autowired
static CityRepository cityRepository;
public static List<Event> eventList = new ArrayList<>();
@RequestMapping
public String eventEntry(Model model) {
model.addAttribute("event", new Event());
model.addAttribute("cities", cityRepository.findAll());
return "eventEntry";
}
}
eventEntry.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Event entry</title>
</head>
<body>
<h3>New event</h3>
<form method="POST" th:object="${event}">
<div class="form-group">
<label for="city">City: </label>
<select th:field="*{city}">
<option value="" >Choose a city</option>
<option th:each="city : ${cities}" th:value="${city}" th:text="${city}"></option>
</select>
<span class="validation-error" th:if="${#fields.hasErrors('city')}" th:errors="*{city}">City Error</span>
</div>
<div class="form-group">
<label for="name">Name: </label>
<input type="text" th:field="*{name}" />
<span class="validation-error" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
</div>
<div class="form-group">
<label for="time">Time: </label>
<input type="datetime-local" th:field="*{time}" />
<span class="validation-error" th:if="${#fields.hasErrors('time')}" th:errors="*{time}">Time Error</span>
</div>
<div class="form-group">
<input type="submit" th:value="Save">
</div>
</form>
</body>
我正在使用嵌入式 H2 数据库,其中包含一个 data.sql
文件,用于将数据填充到数据库中(我没有 schema.sql
文件,因为表是使用注释创建的)。
当查看 H2 数据库控制台并使用 SELECT * FROM CITY 时,我得到了城市列表。
我在 EventController 类的这一行收到 NullPointerException
:model.addAttribute("cities", cityRepository.findAll());
有人能解释一下为什么吗?
最佳答案
删除了存储库前面的static
声明,现在工作正常
关于java - Spring CrudRepository 方法 findAll() 返回一个空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332441/