In this example you will learn how to map components using Hibernate Annotations. Consider the following relationship between Student and Address entity.
According to the relationship each student should have a unique address.
Since the Student and Address entities are strongly related (composition relation), it is better to store them in a single table. The relational model is shown below.
Student class is used to create the STUDENT table.
01.package com.vaannila.student;02. 03.import javax.persistence.Column;04.import javax.persistence.Embedded;05.import javax.persistence.Entity;06.import javax.persistence.GeneratedValue;07.import javax.persistence.Id;08.import javax.persistence.Table;09. 10.@Entity11.@Table(name = "STUDENT")12.public class Student {13. 14.private long studentId;15.private String studentName;16.private Address studentAddress;17. 18.public Student() {19.}20. 21.public Student(String studentName, Address studentAddress) {22.this.studentName = studentName;23.this.studentAddress = studentAddress;24.}25. 26.@Id27.@GeneratedValue28.@Column(name = "STUDENT_ID")29.public long getStudentId() {30.return this.studentId;31.}32. 33.public void setStudentId(long studentId) {34.this.studentId = studentId;35.}36. 37.@Column(name = "STUDENT_NAME", nullable = false, length = 100)38.public String getStudentName() {39.return this.studentName;40.}41. 42.public void setStudentName(String studentName) {43.this.studentName = studentName;44.}45. 46.@Embedded47.public Address getStudentAddress() {48.return this.studentAddress;49.}50. 51.public void setStudentAddress(Address studentAddress) {52.this.studentAddress = studentAddress;53.}54. 55.}


No comments:
Post a Comment