我有两个班级,一个是用户,另一个是种族。两者都有一对一的关联,种族有一个外键user_id但问题是我对种族表中的外键列得到一个空值。我正在使用jsp页面动态设置这些值。
我的映射如下
User Class
@OneToOne(cascade = CascadeType.ALL, mappedBy="user")
public Ethnicity ethnicity;
getter/setter
Ethnicity Class
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
public User user;
getter/setter
要检索数据我正在使用相同的jsp页面设置值。以下是我如何检索数据的代码
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.userId}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.active}</td>
<td>${user.ethnicity.ethnicityId }</td>
<td>${user.ethnicity.nationality }</td>
<td>${user.ethnicity.race }</td>
<td>${user.ethnicity.region }</td>
<td>${user.ethnicity.religion }</td>
</tr>
</c:forEach>
以下是添加用户的功能之一。
@Service
@Transactional(readOnly = true)
public class UserServiceImp implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private Mapper mapper;
@Transactional
public void add(UserDTO userDTO) {
User user = mapper.map(userDTO, User.class);
userRepository.save(user);
}
}
用户服务类扩展了JpaRepository,而对于entitymanager,我正在使用maven依赖。
答案 0 :(得分:0)
应该在种族和用户之间设置关系,即应该为用户设置enthnicity以及为您创建的种族设置用户双向关系。
user.setEthnicity(ethnicity);
ethnicity.setUser(user);
这应该有效。
我写过关于jpa relationshions on www.thejavageek.com的文章,在那里你可以找到关于jpa的多个有用的教程。