[英]How to save foreign key value using Hibernate and JPA annotation
我有兩個班級,一個是用戶,另一個是種族。 兩者都有一對一的關聯,種族有一個外鍵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依賴項。
應該在種族和用戶之間設置關系,即,在創建雙向關系時,應該為用戶設置種族以及為種族設置用戶。
user.setEthnicity(ethnicity); ethnicity.setUser(user);
這應該工作。
我已經在www.thejavageek.com上撰寫了有關jpa關系的文章 ,您可以在其中找到有關jpa的許多有用的教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.