gpt4 book ai didi

java - 使用 JPA 无法获取自动生成的 ID

转载 作者:行者123 更新时间:2023-12-01 16:28:27 25 4
gpt4 key购买 nike

我有两个实体。一个是 UserEntity,另一个是 TaskEntity。

@Entity
@Table(name="user")
public class UserEntity {
@Id
private String userEmail;
private String password;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="user_email")
private List<TaskEntity> tasks;

//getter setter for variables
}
@Entity
@Table(name="task")
public class TaskEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String description;
private String statusDate;
private String status;

//getter setter for variables
}

现在我想基于 userEmail 创建一个新任务,因此我在 DAO 类中执行以下操作:

    @PersistenceContext
EntityManager em;
public Integer addNewTaskByUserEmail(Task task, String userEmail) {
UserEntity userEntity = em.find(UserEntity.class, userEmail);
TaskEntity taskEntity = new TaskEntity();
taskEntity.setName(task.getName());
taskEntity.setDescription(task.getDescription());
taskEntity.setStatus(task.getStatus());
taskEntity.setStatusDate(task.getDate());
userEntity.getTasks().add(taskEntity);
return taskEntity.getId();
}

但是在我的服务类中得到 null 的返回语句中。如何返回自动生成的taskId?

最佳答案

一个可能的问题是您没有保存与用户关联的任务。保存任务然后你也许就能得到taskId。

public Integer addNewTaskByUserEmail(Task task, String userEmail) {
UserEntity userEntity = em.find(UserEntity.class, userEmail);
TaskEntity taskEntity = new TaskEntity();
taskEntity.setName(task.getName());
taskEntity.setDescription(task.getDescription());
taskEntity.setStatus(task.getStatus());
taskEntity.setStatusDate(task.getDate());
em.getTransaction().begin();
em.persist(taskEntity);
em.getTransaction().commit();
userEntity.getTasks().add(taskEntity);
return taskEntity.getId();
}

或者

    @Autowired TaskRepository taskRepository

public Integer addNewTaskByUserEmail(Task task, String userEmail) {
UserEntity userEntity = em.find(UserEntity.class, userEmail);
TaskEntity taskEntity = new TaskEntity();
taskEntity.setName(task.getName());
taskEntity.setDescription(task.getDescription());
taskEntity.setStatus(task.getStatus());
taskEntity.setStatusDate(task.getDate());
taskEntity = taskRepository.save(taskEntity)
userEntity.getTasks().add(taskEntity);
return taskEntity.getId();
}

TaskRepository 所在位置

@Repository
public interface TaskRepository extends JpaRepository<TaskEntity, Integer>
{

}

关于java - 使用 JPA 无法获取自动生成的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62112319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com