我有两个班级(Team
,Coach
):
Team.java:
@Entity
@Table(name="TEAM")
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID_TEAM")
private Long idTeam;
@Column(name = "NAME_TEAM")
private String nameTeam;
@OneToOne
@JoinColumn(name = "ID_COACH")
private Coach coach;
//Getters & Setters...
}
Coach.java:
@Entity
@Table(name="COACH")
public class Coach {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID_COACH")
private Long idCoach;
@Column(name = "NAME_COACH")
private String nameCoach;
@OneToOne
private Team team;
//Getters & Setters...
}
如您所见,它们之间存在OneToOne
关系。
在我的表格中,我从数据库中检索(成功)所有教练。
<form action="add" method="post">
<label for="nameTeam">Team <span style="color: red;">*</span></label>
<input type="text" name="nameTeam" id="nameTeam"/>
<label for="coach">Coach <span style="color: red;">*</span></label>
<select name="coach" id="coach">
<option value="" disabled selected>- Select a coach -</option>
<c:forEach var="coach" items="${coachs}">
<option value="${coach.idCoach}">${coach.nameCoach}</option>
</c:forEach>
</select>
<button type="submit">Add</button>
</form>
所以我从select
元素中选择了一个教练。当我提交表单时,团队会添加到数据库中,但我会在null
字段中获得ID_COACH
。
这是我的Controller
:
@RequestMapping(value = "/team/add", method = RequestMethod.POST)
public String addTeam(Team team) {
this.teamService.add(team);
return "new_team";
}
ConversionService
:
<!-- Conversion Service -->
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converters.ToCoach"/>
</list>
</property>
</bean>
这是我的Converter
:
public class ToCoach implements Converter<Long, Coach> {
@Autowired
CoachRepository coachRepo;
public Coach convert(Long idCoach) {
return this.coachRepo.findOne(idCoach);
}
}