findBy无法使用继承的属性

时间:2019-06-18 14:06:27

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

我有以下模型和存储库:

@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请求通过两个实体的id字段按所有者或电影获取MovieOwnerships。我可以直接使用所有者的ID,但是在请求中使用MovieId似乎已损坏(尽管我可以使用整个Movie对象)。在上面的代码中,前两个findBy很好,但最后一个抛出此异常:

  

由于:java.lang.IllegalArgumentException:无法找到   在此ManagedType上具有给定名称[movieId]的属性   [carrm.app.data.AbstractOwnership]

如果我尝试使用Movie中的另一个属性(例如findByMovieTitle),它将进行编译,但是我无法使其在id上起作用。

有什么办法解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我用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实现错误。

我建议您改用JpaRepository。