【问题标题】:How to save foreign key value using Hibernate and JPA annotation如何使用 Hibernate 和 JPA 注释保存外键值
【发布时间】:2015-03-10 08:04:13
【问题描述】:

我有两个类,一个是用户,另一个是种族。两者都有一对一的关联,种族有一个外键 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 依赖项。

【问题讨论】:

  • 你是如何坚持他们的?你设置关系的双方?你是如何找回它们的?
  • @NeilStockton 请查看更新后的代码。
  • 在哪里?你没有发布 JPA 代码,你没有提到你是如何设置关系并持久化它们的
  • 我是初学者,您能解释一下您需要哪些代码吗?
  • 您将此问题标记为 JPA 和 Hibernate。 JPA API 将数据放入数据库并检索它。您的问题是关于数据库中的数据。因此,应该很清楚这是需要的代码(EntityManager 等)

标签: java mysql hibernate jpa


【解决方案1】:
  • JPA 提供程序不会自动处理之间的关系 基于数据库值的实体。
  • 应用开发者有责任维护关系。
  • 应该在 EthnicityUser 之间设置关系,即应该为用户设置种族,并为种族设置用户,因为您已经创建了双向关系。

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

这应该可行。

我写过关于jpa relationshions on www.thejavageek.com 的文章,您可以在其中找到多个关于 jpa 的有用教程。

【讨论】:

  • 我是一个初学者,这是我第一次体验这项技术,我对这一切知之甚少。您能告诉我在哪里添加此代码吗?
  • @Bilal 请点击答案中提供的链接。它应该可以解决您的问题。如果仍然不方便问。
  • 先生,我正在动态执行所有这些操作,我无法理解将这段代码放在哪里。在我的 java 编码中,我没有使用 entitymanager 来处理所有这些问题。需要帮助。
  • @Bilal,哦!我认为您只使用休眠特定代码而不是 JPA。 EntityManager 对应hibernate中的session。在完成user.setEthnicity(ethnicity);ethnicity.setUser(user); 之后,您需要在用户对象上调用 save 方法基本上您必须从任何一方满足这两种关系。
猜你喜欢
  • 2014-09-28
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 2013-03-03
  • 2011-12-07
  • 1970-01-01
  • 2016-07-16
  • 2020-12-05
相关资源
最近更新 更多