vendredi 7 février 2020

Good way for creation clone of set database collections

I have 12 collections in MongoDB. For example:

public class User {
    private String id;
    private String name;
}

public class Book {
    private String id;
    private String userId;
    private String name;
}

public class Order {
    private String id;
    private String userId;
    private String bookId;
}

And other entities. I have one user, two books and five orders in DB. It is templates. Now I need to create a copy of all these entities. I need to have the same set of entities with different ids. For example, I have this data:

User1 -  templateUserId, John Doe
Book1 -  templateBookId1, templateUserId, Fight Club
Book2 -  templateBookId2, templateUserId, Some adventures
Order1 - templateOrderId1, templateUserId, templateBookId1
Order1 - templateOrderId2, templateUserId, templateBookId2 
...

I need call method like createFromTemplate("templateUserId") and get this data:

User1 -  newUserId, John Doe
Book1 -  newBookId1, newUserId, Fight Club
Book2 -  newBookId2, newUserId, Some adventures
Order1 - newOrderId1, newUserId, newBookId1
Order1 - newOrderId2, newUserId, newBookId2 
...

Now I have one big method.

1) I make the clone of the user and set a new id. 
2) Select a list of books by templateUserId. 
  2.1) Change userId
  2.2) Create new BookId 
  2.3) Fill Map<String, String> where the key is old BookId and value is new BookId.
3) Select all orders by templateUserId
 3.1) if order's BookId contains in the map I get new BookId and set to this order
 3.2) Change OrderId

And I have a lot of entities with relations by ids. I am looking for something easier. Maybe the design pattern. I tried Command, Chain. But I do not understand how to implement it.

I don't have transactions in the project, I don't have relations like oneToMany or ManyToOne like in Hibernate(We have Mongo+Morphia). I need to implement something like a rollback.

In two words - I need a select set of different objects from DB, clone it and save. If I have exception, I will need rollback changes.

Aucun commentaire:

Enregistrer un commentaire