Skip to content

Commit

Permalink
evolve(hibernate): @OneToMay retrieve instructor courses demo
Browse files Browse the repository at this point in the history
  • Loading branch information
chengcyber committed Aug 5, 2018
1 parent 1cd70fd commit ff56ab7
Showing 1 changed file with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.luv2code.hibernate.demo;

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

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 transaction
session.beginTransaction();

// get the instructor from db
int id = 1;
Instructor instructor = session.get(Instructor.class, id);

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

// get courses for instructor
System.out.println("Courses: " + instructor.getCourses());

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

System.out.println("DONE!");

} catch (Exception e) {
e.printStackTrace();
} finally {

// add clean up code
session.close();
factory.close();
}

}

}

0 comments on commit ff56ab7

Please sign in to comment.