我有两个实体。一个是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?
最佳答案
可能的问题是您没有保存与用户关联的任务。保存任务,然后您就可以获取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>
{
}