spring - 扩展 MongoRepository
问题描述
我是 spring 新手,对自动装配如何在扩展 MongoRepository 的接口上工作感到困惑
这是代码:
应用程序.java
package com.db.mongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App implements CommandLineRunner
{
@Autowired
private CustomerRepository repository;
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
repository.deleteAll();
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
}
客户资料库
package com.db.mongo;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CustomerRepository extends MongoRepository {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
客户.java
package com.db.mongo;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
public String id;
public String firstName;
public String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
解决方案
如果您使用的是 spring data mongodb。它能够创建您域中的查询。CrudRepository 为正在管理的实体类提供复杂的 CRUD 功能。有关更多详细信息,请阅读此处
推荐阅读
- java - 从原始存储为 Blob 的嵌入式实体读取
- android - React Native - Reanimated Bottom Sheet:Snapable Container 中的内容只能在 iOS 上滚动
- javascript - 如何将具有元素数组的每个对象的对象列表转换为具有子元素作为属性的对象数组
- javascript - 附加 window.history.back() URL 以将变量传递到上一页
- scala - Scala Play、Apache Spark 和 KuduContext 不兼容
- django - 通过 Django orm 获取最高 x% 的对象集
- python - 如何检查句子特定部分之前的字符串是否与其他行中的任何文本匹配或不匹配(与特定部分之后相同)?
- c++ - WindowsPortableDevice IPortableDeviceContent::Delete 导致我的设备挂起。我该如何解决这个问题?
- python - 如何在python中使用文件名对文件夹中的文件进行排序
- pdf - UiPath 使用 GetText 从 PDF 读取复选框