Search code examples
javamongodbmorphia

How to insert a list of object into mongodb using morphia?


Hi i am trying to insert a List<User> usrList list of object to mongodb using mongodb morphia. I have searched but didn't get anything how to do it. Please help. This is my user pojo class.

@Entity("user")
public class User {

    @Id
    ObjectId id;

    private String name;
    private String rollno;

    public String name() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String rollno() {
        return rollno;
    }
    public void setRollno(String rollno) {
        this.rollno = rollno;
    }
    public ObjectId getId() {
        return id;
    }
    public void setId(ObjectId id) {
        this.id = id;
    }
}

this is main class which call servic to save the list of user object.

public static void main(String[]args){

        ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
        MongoPersistenceService persistenceService = (MongoPersistenceService) context.getBean("persistenceService");
List<User> userLst = new ArrayList<User>();
        User user2 = new User();
        user2.setName("sdfhs");
        user2.setRollno("232123");
        user2.setId(new ObjectId());
        userLst.add(user2);
        persistenceService.addOrUpdateObject(userLst);
}

And this is my service method which i want to use .

 private Datastore ds;
    private AdvancedDatastore ads;
    public void addOrUpdateObject(List<?> objLst) {
                ads.insert(objLst);
        }

Solution

  • You don't need to explicitly insert anything in Morphia.

    Simply add all elements to your list in Java and save the whole entity with Morphia.

    Update: Entities need a no-args constructor for Morphia to persist them. Add

    public User(){
        super();
    }