Created
July 23, 2019 15:01
-
-
Save darbyluv2code/d9755c3de6ff33dc573c08d970347fd2 to your computer and use it in GitHub Desktop.
DeleteDemo - Get id on the fly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.luv2code.hibernate.demo; | |
| import java.util.Scanner; | |
| import org.hibernate.Session; | |
| import org.hibernate.SessionFactory; | |
| import org.hibernate.cfg.Configuration; | |
| import com.luv2code.hibernate.demo.entity.Instructor; | |
| import com.luv2code.hibernate.demo.entity.InstructorDetail; | |
| public class DeleteDemo { | |
| public static void main(String[] args) { | |
| // create session factory | |
| SessionFactory factory = new Configuration() | |
| .configure("hibernate.cfg.xml") | |
| .addAnnotatedClass(Instructor.class) | |
| .addAnnotatedClass(InstructorDetail.class) | |
| .buildSessionFactory(); | |
| // create session | |
| Session session = factory.getCurrentSession(); | |
| try { | |
| // get user id on the fly | |
| System.out.println("Enter instructor id: "); | |
| Scanner in = new Scanner(System.in); | |
| int theId = in.nextInt(); | |
| // start a transaction | |
| session.beginTransaction(); | |
| // get instructor by primary key / id | |
| Instructor tempInstructor = | |
| session.get(Instructor.class, theId); | |
| System.out.println("Found instructor: " + tempInstructor); | |
| // delete the instructors | |
| if (tempInstructor != null) { | |
| System.out.println("Deleting: " + tempInstructor); | |
| // Note: will ALSO delete associated "details" object | |
| // because of CascadeType.ALL | |
| // | |
| session.delete(tempInstructor); | |
| } | |
| // commit transaction | |
| session.getTransaction().commit(); | |
| System.out.println("Done!"); | |
| } | |
| finally { | |
| factory.close(); | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment