开发者

Many to Many Mapping in Hibernate without Collection

Given a classic example of Student and Subject

where they have a many-to-many relationship,

is there any way to map them using POJOs w/o the use of Collections?

e.g.

Student.java

@Entity
class Student{
  @id
  int id;
  String name;
}

Subject.java

@Entity
class Subject{
  开发者_运维问答@id
  int id;
  String desc;
}

Tables

student (id,name)
subject (id,desc)
student_subject (student_id, subject_id) /* both foreign keys */

How will you query all subjects of a student? Is it possible to generate these tables with the given beans?

Thanks in advance!

UPDATE: (I'll just give a background why I ask this ?) My reason for avoiding Collections is that I would like my Service Layer to return data that is not tied to the Persistence Layer. Returning a Student object that has a list of Subjects will make my Service Layer Clients assume that they can get the subjects from the returned student object (then they'll get a LazyLoadException). If I make it EAGER loading, it would be overkill, since in many situations the client would only like the info about the Student and not get all his subjects.


To get all subjects, you need to join the tables like so:

select *
from subject
    join student_subject
    on subject.id = student_subject.subject_id
where
    student_subject.student_id = ?

Is it possible to generate these tables with the given beans?

If you use the many-to-many mapping from Hibernate, it will create the query for you if you add the collections in the POJOs. Without the collection, you have to do it manually.

Note that the collections won't take memory unless:

  1. You use them for the first time
  2. Or you mark them a "load eagerly" in the POJO.

The default is lazy loading, so even if the tables are huge, you won't notice.


The question you should ask is, can you model your classes such that a many-to-many relationship can be established between them without collections?

It would be ideal to use collections and then let Hibernate use lazy-loading to populate the object graph.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜