我刚接触Spring,对于在扩展MongoRepository的接口上自动装配的工作方式感到困惑
代码如下:
App.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);
}
}
}
CustomerRepository
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);
}
Customer.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);
}
}
答案 0 :(得分:0)
如果您使用的是Spring数据mongodb,它可以创建您所在域中的查询。 CrudRepository为正在管理的实体类提供复杂的CRUD功能。有关更多详细信息,请阅读here