首页 > 解决方案 > 扩展 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);
    }
}

标签: springmongodbmaven

解决方案


如果您使用的是 spring data mongodb。它能够创建您域中的查询。CrudRepository 为正在管理的实体类提供复杂的 CRUD 功能。有关更多详细信息,请阅读此处


推荐阅读