我正在尝试构建一个查询,该查询将使用ToDoItems
返回传递User
的所有User
(想要传递登录的JPQL
)。
到目前为止,这是我的内容,不知道如何构建它:
public interface UserRepository extends CrudRepository<User, Long> {
@Query(" from User u ")
public Iterable<ToDoItem> findAllToDosForLoggedInUser(@Param("user") User user);
}
这是我的实体(省略了setter和getters): 的 ToDoItem.java
@Entity
@Table (name = "TO_DO_ITEM")
public class ToDoItem extends BaseEntity {
@Column(name = "TITLE", nullable = false)
private String title;
@Column(name = "COMPLETED")
private boolean completed;
@Column(name = "DUE_DATE", nullable = false)
@Temporal(TemporalType.DATE)
protected Calendar dueDate;
// a ToDoItem is only associated with one user
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name = "USER_ID")
private User user;
// JPA demands empty contructor
public ToDoItem() {}
public ToDoItem(User user, String title, Calendar dueDate) {
this.user = user;
this.title = title;
this.dueDate = dueDate;
}
}
User.java
@Entity
@Table (name = "USERS")
public class User extends BaseEntity {
@Column(name = "USERNAME")
private String username;
@Column(name = "PASSWORD")
private String password;
@Column(name = "EMAIL")
private String email;
// user can have many ToDoItems
@OneToMany(cascade = CascadeType.ALL)
private Set<ToDoItem> toDoItems;
// JPA demands empty constructor
public User() {}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
}
有人还可以检查我的实体是否正确吗?
答案 0 :(得分:1)
您的查询应该是:
@Query(" select td from User u inner join u.toDoItems td where u = :user")
在您的用户实体中,您的地图应具有mappedBy
属性:
@OneToMany(cascade = CascadeType.ALL, mappedBy="user")
private Set<ToDoItem> toDoItems;