Skip to content

Instantly share code, notes, and snippets.

@darbyluv2code
Created February 26, 2019 00:33
Show Gist options
  • Select an option

  • Save darbyluv2code/c5394b87a3153124f1d59ca8cd3a4bda to your computer and use it in GitHub Desktop.

Select an option

Save darbyluv2code/c5394b87a3153124f1d59ca8cd3a4bda to your computer and use it in GitHub Desktop.
CreateStudentDemo (no xml ... file somewhere else on computer ... not on classpath)
package com.luv2code.hibernate.demo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) throws Exception {
// set up properties
Properties myCustomProps = new Properties();
try {
myCustomProps.load(new FileInputStream("c:\\test\\junk\\demo\\mickey-mouse.properties"));
} catch (IOException e) {
e.printStackTrace();
throw e;
}
// create session factory
SessionFactory factory = new Configuration()
.addProperties(myCustomProps)
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student("Paul", "Doe", "[email protected]");
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
// 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