简体   繁体   中英

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:

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 )

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

Any help will be usefull.

Thanks

JPA would be used to store in RDBMS database. DATA JPA Mongo would be used to store documents into 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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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