您的位置:首页 > 数据库 > Mongodb

spring-data-mongodb 对象关联 @DBRef学习 之疑问

2014-04-04 09:50 447 查看
在spring-data-mongodb中,可以使用注解@DBRef来设置对象的关联,@DBRef在包org.springframework.data.mongodb.core.mapping.DBRef;中

例如,如下两个关系实体:

Student(学生实体)
@Document(collection="student")
public class Student {
@Id
private String studentId;
@Indexed(unique=true)
private String studentName;
private int age;
@DBRef
private List<Course> courses;

//setter,getter方法略
}
Course课程实体
@Document(collection="course")
public class Course {
@Id
private String courseId;
@Indexed(unique=true)
private String courseName;
//setter,getter
}


新建一个Student对象,将两门课程赋值给Student对象(注:这两门课程在数据库中并没有),然后保存到数据库。

List<Course> courses = new ArrayList<Course>();
Course math = new Course();
Course english = new Course();

math.setCourseId("c01");
math.setCourseName("math");

english.setCourseId("c02");
english.setCourseName("english");

courses.add(english);
courses.add(math);

Student s = new Student();
s.setAge(21);
s.setCourses(courses);
s.setStudentId("2009011");
s.setStudentName("lklk");

studentService.addStudent(s);


按逻辑来讲,如果数据库中并不存在这两门课程,由于做了关联,在保存Student对象时,应该报错才对,可是为什么能够保存成功。保存的数据如下:

{
"_id" : "2009011",
"_class" : "cn.com.coolcao.springmongo.entity.Student",
"studentName" : "lklk",
"age" : 21,
"courses" : [
{
"$ref" : "course",
"$id" : "c02"
},
{
"$ref" : "course",
"$id" : "c01"
}
]
}


如此可看出,@DBRef已关联成功。可是在course这个collection中并没有c02,c01这两门课程,这样做的意义何在?(集合course此时还是空的,并没任何数据)

对于做了关联的对象之间的保存,删除等操作,spring-data-mongodb并不作检查就直接保存,删除了,这一块我有点不明白,意义何在。这样和内嵌文档的实质区别在哪里?

关于查询:

如果做了关联,查询的时候会是什么样子的呢?

下面我将集合collection中插入三条数据:

/* 0 */
{
"_id" : "c01",
"_class" : "cn.com.coolcao.springmongo.entity.Course",
"courseName" : "math"
}

/* 1 */
{
"_id" : "c02",
"_class" : "cn.com.coolcao.springmongo.entity.Course",
"courseName" : "english"
}

/* 2 */
{
"_id" : "c03",
"_class" : "cn.com.coolcao.springmongo.entity.Course",
"courseName" : "chinese"
}


然后进行查询Student操作:

String id = "2009011";
Student s = studentService.queryById(id);

查询出的结果是:

Student [studentId=2009011, studentName=lklk,age=21, courses=[ Course [courseId=c02, courseName=english], Course[courseId=c01, courseName=math]]]

也就是说,此时查询的时候,spring-data-mongodb会将关联的Course实体也查询了出来,这一点是理想中的结果。

针对我提出的第一点,使用了@DBRef注解做了对象关联后,在插入,删除操作时,并不检查对象之间的关联关系就直接操作了,应该如何解决这个问题。请熟知mongodb的朋友讲解一下,小弟刚开始学mongodb,还请各位不吝赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: