首先,搭好你的环境。配好你的包。
需要的jars包有:mongo-java-driver-2.xx.jar , morphia-0.xx.jar
假设我们有两个类,hotel和address
public class Hotel { private String name; private int stars; private Address address; // ... getters and setters }
和
public class Address { private String street; private String city; private String postCode; private String country; // ... getters and setters }
和我们想保存实例到mongodb,那么我们要添加morphia的注释@,直接上代码:
import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Embedded; import com.google.code.morphia.annotations.Id; import com.google.code.morphia.annotations.Property; import org.bson.types.ObjectId; @Entity public class Hotel { @Id private ObjectId id; private String name; private int stars; @Embedded private Address address; // ... getters and setters }
和
import com.google.code.morphia.annotations.Embedded; @Embedded public class Address { private String street; private String city; private String postCode; private String country; // ... getters and setters }
我们在hotel前加了@Entity,也在address前加了@Embedded。