加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring Boot扩展CrudRepository

发布时间:2020-12-14 16:20:50 所属栏目:Java 来源:网络整理
导读:我在 Spring Boot应用程序中使用Hibernate.我正在为我的所有Model对象创建一个新的CrudRepository,以执行基本的CRUD任务.它们看起来像这样: @Repositorypublic interface FoobarCrudRepo extends CrudRepositoryFoobar,Long {} 但后来我总是需要做一些额外
我在 Spring Boot应用程序中使用Hibernate.我正在为我的所有Model对象创建一个新的CrudRepository,以执行基本的CRUD任务.它们看起来像这样:
@Repository
public interface FoobarCrudRepo extends CrudRepository<Foobar,Long> {
}

但后来我总是需要做一些额外的事情,比如具有不等式的自定义搜索查询等.我遵循这样的模式:

@Repository
public class FoobarDao {

    @PersistenceContext
    EntityManager em;

    public List<Foobar> findFoobarsByDate(Date date) {
        String sql = "select fb from Foobar fb where createdDate > :date";
        ...
        return query.getResultList();
    }
}

我的问题是,我可以将这两个概念合并为一个类吗?我试着把它变成一个抽象类,如下所示:

@Repository
public abstract class FoobarCrudRepo extends CrudRepository<Foobar,Long> {

    @PersistenceContext
    EntityManager em;

    public List<Foobar> findFoobarsByDate(Date date) {
        String sql = "select fb from Foobar fb where createdDate > :date";
        ...
        return query.getResultList();
    }

}

但是Spring没有为它创建一个bean.

我怎么能做到这一点?

谢谢!

解决方法

有很多方法可以实现这一目标.如果你真的需要绝对控制试试这个
interface FoobarRepositoryCustom{
    List<Foobar> findFoobarsByDate(Date date);
}

interface FoobarRepository extends CrudRepository<Foobar,Long>,FoobarRepositoryCustom

public class FoobarRespoitoryImpl implements FoobarRepositoryCustom{
    @PersistenceContext private EntityManager em;


    public List<Foobar> findFoobarsByDate(Date date) {
    String sql = "select fb from Foobar fb where createdDate > :date";
    ...
    return query.getResultList();
    }
}

还可以使用更简单的路径,并可以根据方法名称自动为您生成查询.在你的例子中,你可以将它添加到你的FoobarCrudRepo中,Spring应该做其余的假设Foobar有一个名为CreatedDate的属性

List<Foobar> findByCreatedDateGreaterThan(Date date);

有关Spring如何根据方法名称生成查询的参考,请参阅此http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读