我的数据库中有3个表 - Booking,Restaurant和RestaurantTable。现在我正在尝试创建一个新的预订,其中一个步骤就是添加一个表格。但是当我尝试添加此表时,会出现以下错误:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
这是我的餐厅课程:
@Entity
@Table(name="restaurant")
public class Restaurant {
@Id
@Column(name="id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name="restaurant_name")
private String restaurantName;
@Column(name="address")
private String address;
@OneToMany(mappedBy = "restaurant")
private Set<RestaurantTable> table;
// Getters and setters
我可以改变&#34; table&#34;到FetchType.EAGER,但这会导致其他问题。 我的餐厅课程:
@Entity
@Table(name="restaurant_table")
public class RestaurantTable {
@Id
@Column(name="id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name="table_size")
private Integer tableSize;
@Column(name="table_number")
private Integer tableNumber;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="restaurant_id")
private Restaurant restaurant;
// Getters and setters.
我的BookingController.java:
@RequestMapping(value = "booking/create/{id}", method = RequestMethod.GET)
public String chooseTable(@PathVariable Long id, Model model) {
Booking booking = bookingService.getBooking(id);
Restaurant restaurant = booking.getRestaurant();
Set<RestaurantTable> tableSet = restaurant.getTable();
model.addAttribute("tables", tableSet);
model.addAttribute("booking", booking);
return "chooseTable";
}
.jsp文件发生错误:
<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">
<h2>Create new booking</h2>
<form:form method="POST" modelAttribute="booking" >
<table>
<tr>
<td>Choose a table*:</td>
<td><form:select path="tableNumber">
<form:option value="" label="--- Select ---" />
<form:options items="${tables}" itemValue="tableNumber" itemLabel="tableNumber"/>
</form:select>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
<div>
<a href="/bookings">Back to List</a>
</div>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
感谢任何帮助!
答案 0 :(得分:1)
重构ResturantTable
并删除此类中的提取类型
@ManyToOne
@JoinColumn(name="restaurant_id")
private Restaurant restaurant;
在Resturant
类
@OneToMany(mappedBy = "restaurant",fetch = FetchType.LAZY)
private Set<RestaurantTable> table;
并添加此行bookingService
类方法getBooking(id)
以便将所有数据初始化
booking.getRestaurant().getTable().size();
booking
您的服务方法getBooking(id)
返回对象
答案 1 :(得分:1)
以惰性模式加载相关实体意味着实体将在第一次访问时加载,前提是会话应该是开放且有效的。
会话结束时访问项目会引发LazyInitializationException
。
确保在会话打开时访问项目或将获取类型模式从lazy更改为eager(默认)。