使用Java将Java对象插入MongoDB集合 [英] Inserting Java Object to MongoDB Collection Using Java

查看:467
本文介绍了使用Java将Java对象插入MongoDB集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java将整个Java对象插入到MongoDB集合中。我收到以下错误:

I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:

错误:

Exception in thread "main" java.lang.IllegalArgumentException: can't serialize class net.yogesh.test.Employee
    at org.bson.BSONEncoder._putObjectField(BSONEncoder.java:185)
    at org.bson.BSONEncoder.putObject(BSONEncoder.java:119)
    at org.bson.BSONEncoder.putObject(BSONEncoder.java:65)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:176)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:134)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:129)
    at com.mongodb.DBCollection.save(DBCollection.java:418)
    at net.yogesh.test.test.main(test.java:31)

Emplyoee.java(POJO)

package net.yogesh.test;

import java.io.Serializable;

public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;
    private long no;
    private String name;

    public Employee() {
    }

    public long getNo() {
        return no;
    }

    public void setNo(long no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

主要方法类( test.java)

package net.yogesh.test;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class test {

    public static void main(String[] args) throws UnknownHostException,
            MongoException {

        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("test");

        Employee employee = new Employee();
        employee.setNo(1L);
        employee.setName("yogesh");


        BasicDBObject basicDBObject = new BasicDBObject("Name", employee);

        DBCollection dbCollection = db.getCollection("NameColl");

        dbCollection.save(basicDBObject);   

    }

}

任何人都可以解释为什么我收到这个错误?

Can anybody explain why I am getting this error?

推荐答案

我有点困惑为什么你认为这会在第一名。有些东西需要知道如何将POJO映射到MongoDB文档。目前你没有告诉系统的任何部分如何做到这一点。

I'm a little confused as to why you'd think this would work in the first place. Something needs to know how to map your POJO to a MongoDB document. Currently you're not telling any part of the system how to do that.

你可以使用映射库(Morphia浮现)或使用ReflectionDBObject。两种解决方案(前者比后者更好)允许您将POJO映射到MongoDB文档并返回。

You can either use a mapping library for this (Morphia comes to mind) or use ReflectionDBObject. Either solution (the former a lot more nicely than the latter) allows you to map POJOs to MongoDB documents and back.

这篇关于使用Java将Java对象插入MongoDB集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆