Created
February 26, 2019 00:33
-
-
Save darbyluv2code/c5394b87a3153124f1d59ca8cd3a4bda to your computer and use it in GitHub Desktop.
CreateStudentDemo (no xml ... file somewhere else on computer ... not on classpath)
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.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