Spring Data MongoRepository 接口方法示例

x33g5p2x  于2021-10-15 转载在 Go  
字(1.4k)|赞(0)|评价(0)|浏览(383)

在本文中,我们将探索包 org.springframework.data.mongodb.repository 中 Spring Data 提供的 MongoRepository 接口中可用的方法。 MongoRepository 扩展了 PagingAndSortingRepositoryQueryByExampleExecutor 接口,进一步扩展了 CrudRepository 接口。

MongoRepository 提供了有助于创建 CRUD 应用程序的所有必要方法,它还支持自定义派生查询方法。

public interface MongoRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>{}

在哪里:

T 被文档 POJO 类替换,例如PersonEmployee 等。

ID 是 POJO 类中用于 id 的数据类型,例如StringLong、​​Integer
MongoRepository 接口中只引入了两个新方法,其余的都是从 CrudRepository 接口继承的。

1.insert(S entity)

insert(S *entity*) 方法用于将数据保存/持久化到 MongoDB 数据库中,并返回保存实体的实例。

方法签名:

<S extends T> S insert(S entity);

例子:

School school= new School("Delhi Public1 School", 1998, new String[]{"Science", "Art"}, 600);
         
schoolRepository.insert(school);

2.insert(Iterable<S> entities)

insert(Iterable<S> *entities*) 方法用于一次性保存 MongoDB 数据库中的实体/文档列表。

方法签名:

<S extends T> List<S> insert(Iterable<S> entities);

例子:

List<School> schools = Arrays.asList(
		new School("Delhi Public1 School", 1998, new String[]{"Science", "Art"}, 600),
        new School("Mumbai Public School", 1995, new String[]{"Science"}, 450),
        new School("Jaipur Public School", 2002, new String[]{"Science", "Art", "Commerce"}, 755),
        new School("Kolkata Public School", 1995, new String[]{"Art"}, 300)
);

schoolRepository.insert(schools);

相关文章

微信公众号

最新文章

更多