使用JPA无法获得自动生成的ID

时间:2020-05-31 06:13:40

标签: java hibernate spring-boot spring-data-jpa one-to-many

我有两个实体。一个是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();
    }

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

1 个答案:

答案 0 :(得分:0)

可能的问题是您没有保存与用户关联的任务。保存任务,然后您便可以获取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();
}

OR

    @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>  
{  

}