hibernate之關於關聯映射的綜合應用

來源:互聯網
上載者:User

標籤:hiberntae多對多雙向關聯   hibernate的級聯操作   


【hibernate】之關於關聯映射的綜合應用


1、關聯映射如何處理商務邏輯

2、如何指定中間表

3、如何進行級聯操作

4、如何解決Hibenrate建表過程中主鍵錯亂問題


現在有三張表


Student(學生表),Course(課程表),Score(學生,課程,分數,表)


那麼我們分析商務邏輯可知,學生和課程是多對多的關係,學生和分數表是一對多的關係,課程和分數也是一對多的關係。


直接看Annotations配置,在這裡我所有的配置都是雙向關聯,這樣在分數,課程,學生,之中,可以任意找到彼此!


@Entity@Table(name="c_course")public class Course {private Integer id;private String coursename;private Set<Student> students=new HashSet<Student>();private Set<Score> scores=new HashSet<Score>();@OneToMany(mappedBy="course")//必須指定關係由多的一方維護public Set<Score> getScores() {return scores;}public void setScores(Set<Score> scores) {this.scores = scores;}@ManyToMany//指定中間表是s_score@JoinTable(name="s_score",joinColumns={@JoinColumn(name="course_id")},inverseJoinColumns={@JoinColumn(name="student_id")})public Set<Student> getStudents() {return students;}public void setStudents(Set<Student> students) {this.students = students;}@Id@GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(name="c_coursename")public String getCoursename() {return coursename;}public void setCoursename(String coursename) {this.coursename = coursename;}}

(課程表Course)

@Entity@Table(name="t_student")public class Student {private Integer id;private String name;private Set<Course> courses=new HashSet<Course>();private Set<Score> scores=new HashSet<Score>();@OneToMany(mappedBy="student")public Set<Score> getScores() {return scores;}public void setScores(Set<Score> scores) {this.scores = scores;}@ManyToMany@JoinTable(name="s_score",joinColumns={@JoinColumn(name="student_id")},inverseJoinColumns={@JoinColumn(name="course_id")})public Set<Course> getCourses() {return courses;}public void setCourses(Set<Course> courses) {this.courses = courses;}@Id@GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(name="s_name")public String getName() {return name;}public void setName(String name) {this.name = name;}}

(Student學生表)

@Entity@Table(name="s_score")public class Score {private Integer id;private String score;private Student student;private Course course;@ManyToOne(cascade={CascadeType.ALL})//配置級聯操作@JoinColumn(name="student_id")public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}@ManyToOne(cascade={CascadeType.ALL})@JoinColumn(name="course_id")public Course getCourse() {return course;}public void setCourse(Course course) {this.course = course;}@Id@GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(name="s_score")public String getScore() {return score;}public void setScore(String score) {this.score = score;}}

(分數表,也是中間關聯表,Score)

那麼問題來了,採用Hibernate自動建表,我們看一下建表語句

12:11:08,169 DEBUG SchemaExport:415 -     create table c_course (        id integer not null auto_increment,        c_coursename varchar(255),        primary key (id)    )12:11:08,333 DEBUG SchemaExport:415 -     create table s_score (        id integer not null,        s_score varchar(255),        course_id integer,        student_id integer not null auto_increment,        primary key (student_id, course_id)    )12:11:08,455 DEBUG SchemaExport:415 -     create table t_student (        id integer not null auto_increment,        s_name varchar(255),        primary key (id)    )


我們發現在建表是Hibernate預設將student_id和course_id聯合作為主鍵使用,且student_id還是自增

這樣顯然是不對的,在這裡我也實在想不到,好的辦法,智能採用一個笨的辦法,手動改回來!

大家最好是採用工具操作,因為,你直接create的話,student_id和course_id關聯不上student,course的主鍵ID


ok,到這裡,我們的建表基本完成,下面JunitTest

@Testpublic void add(){try {Configuration cfg=new Configuration();cfg.configure();SessionFactorysessionFactory=cfg.buildSessionFactory();Session session=sessionFactory.openSession();session.beginTransaction();Student student1=new Student();student1.setName("張三1");//Student student2=new Student();//student2.setName("李四");Course c1=new Course();c1.setCoursename("數學1");Course c2=new Course();c2.setCoursename("語文1");//session.save(student1);//session.save(c1);//session.save(student2);//session.save(c2);Score score=new Score();score.setScore("901");score.setCourse(c1);score.setStudent(student1);//張三數學90分session.save(score);Score score2=new Score();score2.setCourse(c2);score2.setScore("100");score2.setStudent(student1);session.save(score2);session.getTransaction().commit();session.close();sessionFactory.close();} catch (HibernateException e) {e.printStackTrace();}}


ok,大家可以看出,為什麼我們最後只需要儲存score就行呢?沒有session.save()student和course,為什麼也能直接儲存資料庫中?這就是

cascade={CascadeType.ALL}

級聯操作,當然我這裡配置的是ALL,其實還有4個參數,大家可以自己慢慢研究!


以上添加成功,那麼我們直接load試一下

public void findTest(){Configuration cfg=new Configuration();cfg.configure();SessionFactorysessionFactory=cfg.buildSessionFactory();Session s=sessionFactory.openSession();s.beginTransaction();Student student=(Student)s.load(Student.class, 2);System.out.println("學生姓名"+student.getName());for(Course course:student.getCourses()){System.out.print("--------"+"課程名稱"+course.getCoursename());for(Score score:course.getScores()){System.out.println("--------"+"課程分數"+score.getScore());}}s.getTransaction().commit();s.close();sessionFactory.close();}

也沒問題

update呢?

public voidupdate(){Configuration cfg=new Configuration();cfg.configure();SessionFactorysessionFactory=cfg.buildSessionFactory();Session s=sessionFactory.openSession();s.beginTransaction();Student student=(Student)s.load(Student.class,1);//我們現在把查詢出來語文成績改為0分for(Course course:student.getCourses()){System.out.println(course.getCoursename());if("語文".equals(course.getCoursename())){for(Score score:course.getScores()){if(score.getStudent().getId().equals(student.getId())){score.setScore("0");s.update(score);}}}} s.getTransaction().commit();s.close();sessionFactory.close();}


刪除?


@Testpublic void deleteObj(){Configuration cfg=new Configuration();cfg.configure();SessionFactorysessionFactory=cfg.buildSessionFactory();Session s=sessionFactory.openSession();s.beginTransaction();Student student=(Student)s.load(Student.class,3);s.delete(student);s.getTransaction().commit();s.close();sessionFactory.close();}



ok,到這裡基本上,完成Hibernate關聯映射的基本操作!


注意,多對多刪除的時候,我們一般刪除的是中間表資料?但是往往由於外部索引鍵關聯的關係,Hibernate會刪除另一張表中的資料來解除關聯關係,這就不對了!後續再探討!




本文出自 “諾言永遠依戀小柴、、、” 部落格,請務必保留此出處http://1936625305.blog.51cto.com/6410597/1569149

hibernate之關於關聯映射的綜合應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.