问题
I'm making my first steps with the Play! Framework (v2.1-rc1) with Java and now I've faced my first problem with ebean. I have a navigation entity with a ManyToOne relationship to itself. As soon as I try to access the title field in a parentNavigation, I get the following error:
[EntityNotFoundException: Bean has been deleted - lazy loading failed]
As I found out, the error only appears if the parent navigation does not exist in the database. Shouldn't I receive an empty navigation object in this case?
Navigation Entity:
package models;
import javax.persistence.*;
import play.db.ebean.*;
@Entity
public class Navigation extends Model {
@Id
public Long id;
@Column(name="c_title")
public String title;
@Column(name="id_parent")
public Long parentId;
@ManyToOne()
@JoinColumn(name="id_parent")
public Navigation parentNavigation;
public static Finder<Long,Navigation> find = new Finder<Long,Navigation>(
Long.class, Navigation.class
);
}
My action in the controller:
public static Result index() {
Navigation navigation = Navigation.find.byId(2L); // this one doesn't work, but the entry with ID 30 does
return ok(views.html.app.index.render(navigation));
}
And my view:
@(navigation: Navigation)
@main("Welcome to Play 2.0") {
This navigation: @navigation.title <br>
Parent: @navigation.parentNavigation.title
}
回答1:
If I understand correctly, you have a row with its parent_id
column containing 2
(for example), but there is no row with ID 2
in the table.
If so, then it's normal to get an exception. Clean your data by setting all those inexistent parent_id
to NULL, and add a foreign key constraint to the parent_id
column so that this situation never happens anymore.
回答2:
In very general it's always better to check if relation isn't null before trying to access it:
This navigation: @navigation.title <br>
Parent: @if(navigation.parentNavigation != null){@navigation.parentNavigation.title} else {This nav has no parent}
Of course you can skip the else
clause if it isn't required
来源:https://stackoverflow.com/questions/13779600/entitynotfoundexception-bean-has-been-deleted-lazy-loading-failed