提供两个实体,电影和导演。
@Entity
public class Movie extends BaseEntity {
private static final long serialVersionUID = -1545404740388837658L;
@Column(name="movieName", nullable=false, length=200)
private String movieName;
@Column(name="year", nullable=false)
private Integer year;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="director_id")
private Director director;
//setter, getter
}
@Entity
public class Director extends BaseEntity {
@NotEmpty
@Column(nullable = false, length=50)
private String name;
//setter, getter
}
JSP中有一个表单
<form:form action="saveMovie" commandName="movie" >
<p><label>Movie Name</label><form:input path="movieName" /></p>
<p><label>Year</label><form:input path="year" /></p>
<p><label>Director</label><form:input id="txtDirector" path="director.id" /></p>
<p>
<input type="submit" name="Save" />
</p>
</form:form>
这是没有Director处理的原始控制器
@RequestMapping(value="/saveMovie", method = RequestMethod.POST)
public String saveMovie(@ModelAttribute Movie movie, BindingResult result, SessionStatus status, ModelMap model) {
getMovieModel().saveMovie(movie); //get a DAO to persist a Movie
List<Movie> movies = getMovieModel().getAllMovies(); //reload all Movies
model.put("allMovies", movies);
return "test/allMovies";
}
提交电影时加载现有Director实体的最佳模式是什么? 非常感谢
答案 0 :(得分:0)
如果导演对Movie是强制性的,那么最好使用FetchType = EAGER加载。 此外,如果您需要每个Movie实体的Director对象用于某些逻辑,那么最好使用EAGER。
如果您使用FetchType = LAZY,那么当您调用movie.getDirector()方法时,它将获取Director实体。
答案 1 :(得分:0)
我制定了一个解决方案,但不确定它是“将现有实体与将要保留在数据库中的新实体相关联”的最佳模式。在Spring MVC模型中。
这是我的代码修订版:
@RequestMapping(value="/saveMovie", method = RequestMethod.POST)
public String saveMovie(@ModelAttribute("movie") Movie movie, @ModelAttribute("director") Director director, BindingResult result, SessionStatus status, ModelMap model) {
/*please note that parameter "director" is newly added */
logger.trace(movie.getMovieName() + "," + movie.getYear());
movie.setDirector(director); // <-- newly added
getMovieModel().saveMovie(movie);
List<Movie> movies = getMovieModel().getAllMovies();
model.put("allMovies", movies);
return "test/allMovies";
}
@ModelAttribute("director")
public Director loadDirector(@RequestParam(value="director.id", required=false) Long id) {
Director director = null;
if (id != null)
director = getDirectorModel().loadDirector(id);
return director;
}
请参阅方法“loadDirector”注释@ModelAttribute,以便在每次调用控制器之前,首先调用loadDirector()。我可以检查请求参数“director.id”是否为null。 如果director id不为null,我可以从数据库加载Director,以便在调用saveMovie()时使用它。 别忘了打电话
movie.setDirector(director);
在saveMovie()方法中。