0

我有这个代码:

Candidate candidate = new Candidate();
candidate.setName("testUser");
candidate.setPhone("88888");
candidateService.add(candidate);
sessionFactory.getCurrentSession().flush();
return candidate;

候选服务标记为@Transactional

你能解释一下为什么在执行candidateService.add(candidate); 候选人后获取 id 字段值。也许是正常的?

candidateService.add(candidate) realization:

public void add(Candidate candidate) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String login = auth.getName();
     User user =  utilService.getOrSaveUser(login);
     candidate.setAuthor(user);
     candidateDao.add(candidate);
}

@Override
public Integer add(Candidate candidate) throws HibernateException{
    Session session = sessionFactory.getCurrentSession();
    if (candidate == null) {
        return null;
    }
    Integer id = (Integer) session.save(candidate);
    return id;

}

我认为如果候选人处于持久状态,就会发生这种情况。

我把事情搞糟。

4

1 回答 1

1

由于 ID 是候选表的主键,因此当您将其添加到数据库时,会生成一个 ID,并由 save 方法返回。

如果您看到save method的文档。

持久化给定的瞬态实例,首先分配一个生成的标识符。(或者,如果使用分配的生成器,则使用标识符属性的当前值。)如果关联映射为 cascade="save-update",则此操作级联到关联的实例。

返回:生成的标识符

于 2013-09-26T06:59:33.447 回答