簡體   English   中英

如何使用Hibernate和JPA批注保存外鍵值

[英]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依賴項。

  • JPA提供程序不會根據數據庫值自動處理實體之間的關系。
  • 維護關系是應用程序開發人員的責任。
  • 應該在種族用戶之間設置關系,即,在創建雙向關系時,應該為用戶設置種族以及為種族設置用戶。

      user.setEthnicity(ethnicity); ethnicity.setUser(user); 

這應該工作。

我已經在www.thejavageek.com上撰寫了有關jpa關系的文章 ,您可以其中找到有關jpa的許多有用的教程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM