![](/img/trans.png)
[英]Spring and Hibernate web application: how to resolve 'org.hibernate.LazyInitializationException?
[英]org.hibernate.LazyInitializationException (Spring/Hibernate)
我的數據庫中有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
我可以將“表”更改為FetchType.EAGER,但這會導致其他問題。 我的RestaurantTable類:
@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>
任何幫助表示贊賞!
重構ResturantTable
並刪除此類中的獲取類型
@ManyToOne
@JoinColumn(name="restaurant_id")
private Restaurant restaurant;
在Resturant
類中添加訪Resturant
類型
@OneToMany(mappedBy = "restaurant",fetch = FetchType.LAZY)
private Set<RestaurantTable> table;
並將這行添加到bookingService
類方法getBooking(id)
以getBooking(id)
所有數據
booking.getRestaurant().getTable().size();
booking
您的服務方法getBooking(id)
返回對象
在延遲模式下加載相關實體意味着,如果會話應該是開放且有效的,則當實體首次被訪問時它們將被加載。
在會話關閉時訪問項目將引發LazyInitializationException
。
確保在會話打開時訪問項目,或將獲取類型模式從“懶惰”更改為“渴望”(默認)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.