如何使用 Hibernate 和 JPA 注释保存外键值
How to save foreign key value using Hibernate and JPA annotation
我有两个 classes 一个是用户,另一个是种族。两者都有一对一的关联,种族有一个外键 user_id 但问题是我在种族 table 中的外键列中得到一个空值。我正在使用 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);
}
}
用户服务 class 扩展了 JpaRepository 并且对于 entitymanager 我正在使用 maven 依赖项。
- JPA provider 不会自动处理两者之间的关系
基于数据库值的实体。
- 应用开发者有责任维护关系。
应该在种族和用户之间设置关系,即也应该为用户设置种族作为种族的用户集,因为您已经创建了双向关系。
user.setEthnicity(ethnicity);
ethnicity.setUser(user);
这应该有效。
我写过关于 jpa relationshions on www.thejavageek.com 的文章,您可以在其中找到有关 jpa 的多个有用教程。
我有两个 classes 一个是用户,另一个是种族。两者都有一对一的关联,种族有一个外键 user_id 但问题是我在种族 table 中的外键列中得到一个空值。我正在使用 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);
}
}
用户服务 class 扩展了 JpaRepository 并且对于 entitymanager 我正在使用 maven 依赖项。
- JPA provider 不会自动处理两者之间的关系 基于数据库值的实体。
- 应用开发者有责任维护关系。
应该在种族和用户之间设置关系,即也应该为用户设置种族作为种族的用户集,因为您已经创建了双向关系。
user.setEthnicity(ethnicity); ethnicity.setUser(user);
这应该有效。
我写过关于 jpa relationshions on www.thejavageek.com 的文章,您可以在其中找到有关 jpa 的多个有用教程。