使用 Java 将 Java 对象插入 MongoDB 集合
我正在尝试使用Java将整个Java对象插入MongoDB集合中。我收到以下错误:
错误:
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;
}
}
主要方法类(测试.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);
}
}
任何人都可以解释为什么我收到这个错误吗?