【问题标题】:findBy not working with inherited propertiesfindBy 不使用继承的属性
【发布时间】:2019-06-19 18:21:40
【问题描述】:

我有以下模型和存储库:

@Entity
@Table(name = "db_user", uniqueConstraints = { @UniqueConstraint(columnNames = "email") })
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_user")
    @SequenceGenerator(name = "seq_user", sequenceName = "seq_user")
    @Column(name = "id")
    private Long id;

    // ...
}

@Entity
@Table(name = "movie")
public class Movie extends AbstractItem {
    // Id column inherited from AbstractItem

    // ...
}

@Entity
@Table(name = "movie_user")
public class MovieOwnership extends AbstractOwnership {

    @ManyToOne
    private Movie movie;

    // ...
}

@MappedSuperclass
public abstract class AbstractOwnership{

    @Id
    @SequenceGenerator(name = "seq_default", sequenceName = "seq_default")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_default")
    @Column(name = "id")
    private Long id;

    @ManyToOne
    private User owner;

    // ...
}


public interface MovieOwnershipRepository extends QueryDslJpaRepository<MovieOwnership, Long> {

    List<MovieOwnership> findByOwnerId(Long ownerId);

    MovieOwnership findByOwnerIdAndMovie(Long ownerId, Movie movieId);

    List<MovieOwnership> findByOwnerIdAndMovieIdIn(Long ownerId, Set<Long> movieIds);
}

我正在尝试使用 Spring 的 findBy 请求来按所有者或电影获取 MovieOwnership,使用两个实体的 id 字段。我可以直接使用所有者的 id,但是在我的请求中使用 MovieId 似乎是错误的(尽管我可以使用整个 Movie 对象)。在上面的代码中,前两个 findBy 没问题,但最后一个抛出这个异常:

原因:java.lang.IllegalArgumentException:无法定位 此 ManagedType 上具有给定名称 [movieId] 的属性 [carrm.app.data.AbstractOwnership]

如果我尝试使用 Movie 中的另一个属性(如 findByMovieTitle),它会编译,但我无法让它在 id 上工作。

知道如何解决这个问题吗?

【问题讨论】:

  • movieId 属性在哪里定义?
  • 这三种方法你调用的是哪一种?
  • 这段代码还能编译吗?你有一个扩展类的接口(QuerydslJpaRepository)
  • @XavierBouclet movieId 属性是指MovieOwnership 的movie 字段的id 字段,就像ownerId 是指User 的id 属性一样。
  • @SimonMartinelli 我成功调用了前两种方法,但添加第三种方法会破坏应用程序。

标签: spring-boot jpa spring-data-jpa


【解决方案1】:

我尝试使用 JpaRepository 而不是 QueryDslJpaRepository。

SQL 生成正确:

select movieowner0_.id as id1_1_, movieowner0_.owner_id as owner_id2_1_, movieowner0_.movie_id as movie_id3_1_ 
from movie_ownership movieowner0_ 
left outer join user user1_ on movieowner0_.owner_id=user1_.id 
left outer join movie movie2_ on movieowner0_.movie_id=movie2_.id 
where user1_.id=? and (movie2_.id in (?))

所以一定是QueryDslJpaRepository实现的bug。

我建议你改用 JpaRepository。

【讨论】:

  • 我不知道我的自定义存储库到底出了什么问题,因为它可以很好地与用户的属性配合使用,但是将其更改为 JpaRepository 是可行的。
  • QueryDslJpaRepository 已弃用,不应再使用 docs.spring.io/spring-data/jpa/docs/current/api/org/…
猜你喜欢
  • 2014-02-03
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 2017-05-12
  • 1970-01-01
  • 2017-08-10
  • 2019-06-12
相关资源
最近更新 更多