我在用户和任务之间有一对多的关系(一个用户有很多任务)。
SELECT G.accountability, G.title, G.interval, G.description, U.user_name
FROM user U
LEFT OUTER JOIN GOAL G on (G.USER_ID = U.USER_ID)
我将数据插入到数据库中,其中每个任务中的外键关联都与用户ID相对应。在JPA中是否可以基本上说:
Given the user ID here are all the tasks
这是我简单的回购
import com.habicus.core.model.Goal;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface GoalRepository extends JpaRepository<Goal, Long> {
}
答案 0 :(得分:1)
您可以使用以下查询选择任务,这些任务将使用userId加入任务。
@Query("select task from User user join user.task task where user.id = :userId")
List<Task> getTasksByUserId(@Param("userId") Integer userId)
如果要选择特定列作为查询,则如下所示。
@Query("select task.accountability, task.title, task.interval, task.description, user.user_name from User user join user.task task where user.id = :userId")
List<Object[]> getTasksByUserId(@Param("userId") Integer userId)
如果选择第二种选项,您也可以使用预测。有关详细信息,请参阅here。
答案 1 :(得分:0)
假设您的目标和用户实体创建如下:
@Entity
class User {
@Id
private Long id;
@OneToMany
private List<Goal> tasks;
...
}
@Entity
class Goal {
@Id
private Long id;
@ManyToOne
private User user;
...
}
一个选项是通过id加载用户并返回任务:
userRepository.findById(userId).getTasks()
另一个选择是将以下方法添加到 GoalRepository :
List<Goal> findByUserId(Long userId);
Spring Data JPA剥离 findBy 前缀,并使用其余部分构建WHERE子句。首先,它会查看目标中是否存在 userId 属性。如果没有,则会检查用户属性,该属性又包含 id 属性。
PS:假设你指的是同一个目标和任务。