Created
February 26, 2019 00:31
-
-
Save darbyluv2code/ae639963bbc3306b221bba27201914bc to your computer and use it in GitHub Desktop.
CreateStudentDemo (no xml ... custom file name)
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.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 props = new Properties(); | |
| try { | |
| props.load(CreateStudentDemo.class.getClassLoader().getResourceAsStream("mickey-mouse.properties")); | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| throw e; | |
| } | |
| // create session factory | |
| SessionFactory factory = new Configuration() | |
| .addProperties(props) | |
| .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