如何使 JPA 查询使用原始 ID 而不是托管实例?
How to make a JPA query use primitive ID instead of managed instance?
我试过了,但找不到更好的标题,所以看起来很奇怪,但问题其实很简单...
我有一个使用外键的 JPA 查询,默认情况下 JPA 将托管实体作为外键来执行查询,有什么办法可以通过长 ID 代替吗?
示例:
@Entity
@Table(name = "user")
public class User {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "user")
private Set<Item> entries = new HashSet<>();
}
@Entity
@Table(name = "item")
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(targetEntity = User.class, optional = false, fetch = FetchType.LAZY)
private User user;
}
@Repository
public interface ItemRepository extends PagingAndSortingRepository<User, Long> {
// @formatter:off
@Query("SELECT item FROM Item item WHERE (:user is null OR :user = item.user)")
Page<Item> findByUser(@Param("user")User user, Pageable pageable);
//@formatter:on
}
我想要的不是将用户实体传递到存储库 class,而是只传递它的 ID,这样我就可以将 id 作为参数并避免对数据库进行一次查询,只是为了从中检索用户它的编号
我该怎么做
好吧,只需将参数设为 Long
然后
@Query("SELECT item FROM Item item WHERE (:userId is null OR :userId = item.user.id)")
Page<Item> findByUser(@Param("userId")Long userId, Pageable pageable);
我试过了,但找不到更好的标题,所以看起来很奇怪,但问题其实很简单...
我有一个使用外键的 JPA 查询,默认情况下 JPA 将托管实体作为外键来执行查询,有什么办法可以通过长 ID 代替吗?
示例:
@Entity
@Table(name = "user")
public class User {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "user")
private Set<Item> entries = new HashSet<>();
}
@Entity
@Table(name = "item")
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(targetEntity = User.class, optional = false, fetch = FetchType.LAZY)
private User user;
}
@Repository
public interface ItemRepository extends PagingAndSortingRepository<User, Long> {
// @formatter:off
@Query("SELECT item FROM Item item WHERE (:user is null OR :user = item.user)")
Page<Item> findByUser(@Param("user")User user, Pageable pageable);
//@formatter:on
}
我想要的不是将用户实体传递到存储库 class,而是只传递它的 ID,这样我就可以将 id 作为参数并避免对数据库进行一次查询,只是为了从中检索用户它的编号
我该怎么做
好吧,只需将参数设为 Long
然后
@Query("SELECT item FROM Item item WHERE (:userId is null OR :userId = item.user.id)")
Page<Item> findByUser(@Param("userId")Long userId, Pageable pageable);