One To Many

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8
At a glance
Powered by AI
The document discusses the mapping of entities in a one-to-many relationship using Hibernate annotations. The Instructor entity is mapped to multiple Course entities using the @OneToMany annotation, while each Course is mapped to a single Instructor using the @ManyToOne annotation.

The Instructor entity has a @OneToMany relationship with the Course entity, allowing an instructor to have multiple courses. The Course entity has a @ManyToOne relationship with Instructor, allowing a course to be associated with a single instructor.

You can retrieve the courses for a specific instructor by getting the instructor object from the session using its ID, and then calling the getCourses() method on the instructor object. This will return the list of courses associated with that instructor.

Instructor.java 225 solution-code-hibernate-hb-03-one-to-many.

zip

package com.luv2code.hibernate.demo.entity;

import java.util.ArrayList; import java.util.List;

import javax.persistence.CascadeType; import javax.persistence.Column;


import javax.persistence.Entity; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.OneToMany;
import javax.persistence.OneToOne; import javax.persistence.Table;

@Entity
@Table(name="instructor")
public class Instructor {

// annotate the class as an entity and map to db table

// define the fields

// annotate the fields with db column names

// ** set up mapping to InstructorDetail entity

// create constructors

// generate getter/setter methods

// generate toString() method

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@Column(name="email")
private String email;

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="instructor_detail_id")
private InstructorDetail instructorDetail;

@OneToMany(mappedBy="instructor",
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
private List<Course> courses;

public Instructor() { }

public Instructor(String firstName, String lastName, String email) {


this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public int getId() { return id; }

1
public void setId(int id) {
this.id = id;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public InstructorDetail getInstructorDetail() {


return instructorDetail;
}

public void setInstructorDetail(InstructorDetail instructorDetail) {


this.instructorDetail = instructorDetail;
}

@Override
public String toString() {
return "Instructor [id=" + id + ", firstName=" + firstName + ", lastName="
+ lastName + ", email=" + email + ", instructorDetail=" + instructorDetail + "]";
}

public List<Course> getCourses() {


return courses;
}

public void setCourses(List<Course> courses) {


this.courses = courses;
}

// add convenience methods for bi-directional relationship


public void add(Course tempCourse) {

if (courses == null) {
courses = new ArrayList<>();
}

courses.add(tempCourse);

tempCourse.setInstructor(this);
}
}

2
Course.java

package com.luv2code.hibernate.demo.entity;

import javax.persistence.CascadeType; import javax.persistence.Column;


import javax.persistence.Entity; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="course")
public class Course {

// define our fields

// define constructors

// define getter setters

// define tostring

// annotate fields

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="title")
private String title;

@ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE,


CascadeType.DETACH, CascadeType.REFRESH})
@JoinColumn(name="instructor_id")
private Instructor instructor;

public Course() { }

public Course(String title) { this.title = title; }

public int getId() { return id; }

public void setId(int id) { this.id = id; }

public String getTitle() { return title; }

public void setTitle(String title) { this.title = title; }

public Instructor getInstructor() { return instructor; }

public void setInstructor(Instructor instructor) {


this.instructor = instructor;
}

@Override
public String toString() {
return "Course [id=" + id + ", title=" + title + "]";
}

3
CreateInstructorDemo.java

package com.luv2code.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.luv2code.hibernate.demo.entity.Course;
import com.luv2code.hibernate.demo.entity.Instructor;
import com.luv2code.hibernate.demo.entity.InstructorDetail;

public class CreateInstructorDemo {

public static void main(String[] args) {

// create session factory


SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();

// create session
Session session = factory.getCurrentSession();

try {
// create the objects
Instructor tempInstructor =
new Instructor("Susan", "Public",
"[email protected]");

InstructorDetail tempInstructorDetail =
new InstructorDetail(
"http://www.youtube.com", "Video Games");

// associate the objects


tempInstructor.setInstructorDetail(tempInstructorDetail);

// start a transaction
session.beginTransaction();

// save the instructor

// Note: this will ALSO save the details object


// because of CascadeType.ALL
//
System.out.println("Saving instructor: " + tempInstructor);
session.save(tempInstructor);

// commit transaction
session.getTransaction().commit();

System.out.println("Done!");
}

finally {
// add clean up code
session.close();
factory.close();
}
}
}
4
CreateCoursesDemo.java

package com.luv2code.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.luv2code.hibernate.demo.entity.Course;
import com.luv2code.hibernate.demo.entity.Instructor;
import com.luv2code.hibernate.demo.entity.InstructorDetail;

public class CreateCoursesDemo {

public static void main(String[] args) {

// create session factory


SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();

// create session
Session session = factory.getCurrentSession();

try {

// start a transaction
session.beginTransaction();

// get the instructor from db


int theId = 1;
Instructor tempInstructor = session.get(Instructor.class, theId);

// create some courses


Course tempCourse1 = new Course("Air Guitar - The Ultimate Guide");
Course tempCourse2 = new Course("The Pinball Masterclass");

// add courses to instructor


tempInstructor.add(tempCourse1);
tempInstructor.add(tempCourse2);

// save the courses


session.save(tempCourse1);
session.save(tempCourse2);

// commit transaction
session.getTransaction().commit();

System.out.println("Done!");
}
finally {

// add clean up code


session.close();

factory.close();
}
}
}
5
GetInstructorCoursesDemo.java

package com.luv2code.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.luv2code.hibernate.demo.entity.Course;
import com.luv2code.hibernate.demo.entity.Instructor;
import com.luv2code.hibernate.demo.entity.InstructorDetail;

public class GetInstructorCoursesDemo {

public static void main(String[] args) {

// create session factory


SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();

// create session
Session session = factory.getCurrentSession();

try {

// start a transaction
session.beginTransaction();

// get the instructor from db


int theId = 1;
Instructor tempInstructor = session.get(Instructor.class, theId);

System.out.println("Instructor: " + tempInstructor);

// get courses for the instructor


System.out.println("Courses: " + tempInstructor.getCourses());

// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {

// add clean up code


session.close();
factory.close();
}
}

6
DeleteCourseDemo.java

package com.luv2code.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Course;
import com.luv2code.hibernate.demo.entity.Instructor;
import com.luv2code.hibernate.demo.entity.InstructorDetail;

public class DeleteCourseDemo {

public static void main(String[] args) {

// create session factory


SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();

// create session
Session session = factory.getCurrentSession();
try {

// start a transaction
session.beginTransaction();

// get a course
int theId = 10;
Course tempCourse = session.get(Course.class, theId);

// delete course
System.out.println("Deleting course: " + tempCourse);

session.delete(tempCourse);
// commit transaction
session.getTransaction().commit();

System.out.println("Done!");
}
finally {
// add clean up code
session.close();
factory.close();
}
}
}

7
8

You might also like