使用Spring Data JPA,是否可以像这样做:
能否在运行时将图形名称传递到方法中,并使用一组需要的集合调用加载操作?这种构造方式不起作用,会产生编译时错误。对此的任何尝试都失败了...
因此,我在用户类中有多个集合,我希望根据条件进行加载。
现在,我只需要像这样隐式地声明所有方法:
public interface UserDao extends CrudRepository<User, Long> {
@EntityGraph(value = :graphName, type = EntityGraph.EntityGraphType.LOAD)
@Query(value = "SELECT DISTINCT u FROM User u")
List<User> findAllWithDetailsByGraphName(@Param(value="graphName") String graphName);
}
能否在运行时将图形名称传递到方法中,并使用一组需要的集合调用加载操作?这种构造方式不起作用,会产生编译时错误。对此的任何尝试都失败了...
因此,我在用户类中有多个集合,我希望根据条件进行加载。
@Entity
@Table(name="user")
@NamedEntityGraphs({
@NamedEntityGraph(name = "User.details", attributeNodes = {
@NamedAttributeNode("phones"), @NamedAttributeNode("emails"), @NamedAttributeNode("pets")}),
@NamedEntityGraph(name = "User.phones", attributeNodes =
{@NamedAttributeNode("phones")}),
@NamedEntityGraph(name = "User.emails", attributeNodes =
{@NamedAttributeNode("emails")}),
@NamedEntityGraph(name = "User.pets", attributeNodes =
{@NamedAttributeNode("pets")})
})
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO, generator="native")
@GenericGenerator(name = "native", strategy = "native")
@Column(name="user_id")
private Long userId;
@Column(name="name")
private String name;
// more fields omitted
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Phone> phones;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Email> emails;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Pet> pets;
}
现在,我只需要像这样隐式地声明所有方法:
@EntityGraph(value = "User.phones", type = EntityGraph.EntityGraphType.LOAD)
@Query(value = "SELECT DISTINCT u FROM User u")
List<User> findAllWithPhones();
感谢您的建议!
(谢谢您的建议!)