简体   繁体   English

如何使用Spring Data MongoDB或Spring Data Jpa

[英]How can I use Spring Data MongoDB or Spring Data Jpa

I'm trying to use spring data mongoDB OR spring data jpa without duplicating too much code: 我正在尝试使用spring数据mongoDB或spring数据jpa而不重复太多代码:

I have a Customer model: 我有一个客户模型:

@Document
@Entity
public class Customer {

    @Id
    @GeneratedValue
    private BigInteger id;

    private String firstName;
    private 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=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

Then, I have two packages: repository.jpa and repository.mongo (as mentioned in example 11 here ) 然后,我有两个包:repository.jpa和repository.mongo(如实施例11中提到在这里

public interface CustomerJpaRepository extends CrudRepository<Customer, BigInteger> {
    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);
}

public interface CustomerMongoRepository extends MongoRepository<Customer, BigInteger> {
    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);
}

And finally the Application: 最后是应用程序:

@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "hello.repository.jpa")
@EnableMongoRepositories(basePackages = "hello.repository.mongo")
@EnableTransactionManagement
public class Application implements CommandLineRunner {

    @Autowired
    private CustomerMongoRepository repositoryMongo;
    @Autowired
    private CustomerJpaRepository repositoryJpa;


    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        System.out.println("-------------------------------");
        System.out.println("MongoDB");
        repositoryMongo.deleteAll();

        // save a couple of customers
        repositoryMongo.save(new Customer("Alice", "Smith"));
        repositoryMongo.save(new Customer("Bob", "Smith"));

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repositoryMongo.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFirstName('Alice'):");
        System.out.println("--------------------------------");
        System.out.println(repositoryMongo.findByFirstName("Alice"));

        System.out.println("Customers found with findByLastName('Smith'):");
        System.out.println("--------------------------------");
        for (Customer customer : repositoryMongo.findByLastName("Smith")) {
            System.out.println(customer);
        }

        System.out.println("-------------------------------");
        System.out.println("JPA");
        repositoryJpa.deleteAll();

        // save a couple of customers
        repositoryJpa.save(new Customer("Ludo2", "Smith"));
        repositoryJpa.save(new Customer("John2", "Smith"));

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repositoryJpa.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFirstName('Ludo2'):");
        System.out.println("--------------------------------");
        System.out.println(repositoryJpa.findByFirstName("Ludo2"));

        System.out.println("Customers found with findByLastName('Smith'):");
        System.out.println("--------------------------------");
        for (Customer customer : repositoryJpa.findByLastName("Smith")) {
            System.out.println(customer);
        }
    }
}

What I would like to do is: 我想做的是:

Choose to use Jpa or Mongo (but not both) and avoid duplicated code in Application class 选择使用Jpa或Mongo(但不能同时使用两者),并避免在Application类中重复代码

Any help will be usefull. 任何帮助将是有用的。

Thanks 谢谢

JPA would be used to store in RDBMS database. JPA将用于存储在RDBMS数据库中。 DATA JPA Mongo would be used to store documents into Mongo. DATA JPA Mongo将用于将文档存储到Mongo中。

So you have to make a decision which database you need to user 因此,您必须决定需要使用哪个数据库

But if your use case is to store all documents in mongo and retrieve few of to and persist in db and query using sql, I think your code should work. 但是,如果您的用例是将所有文档都存储在mongo中,而只检索其中的几个文档并保留在db中,并使用sql查询,那么我认为您的代码应该可以工作。

You could create a common interface and extend your repository interface and use some kind of Strategy pattern to use the appropriate repo 您可以创建一个通用接口并扩展您的存储库接口,并使用某种策略模式来使用适当的存储库

public interface CommonRepo{
    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM