Skip to content

Instantly share code, notes, and snippets.

@darbyluv2code
Created July 23, 2019 15:01
Show Gist options
  • Save darbyluv2code/d9755c3de6ff33dc573c08d970347fd2 to your computer and use it in GitHub Desktop.
Save darbyluv2code/d9755c3de6ff33dc573c08d970347fd2 to your computer and use it in GitHub Desktop.
DeleteDemo - Get id on the fly
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