Last active
July 23, 2018 07:47
-
-
Save anas-didi95/dba8d9ecee1109c1244515351f9d82e6 to your computer and use it in GitHub Desktop.
hibernate_bootstrap-hibernate-initialization.java
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 dao; | |
import org.hibernate.HibernateException; | |
import org.hibernate.Session; | |
import org.hibernate.SessionFactory; | |
import org.hibernate.Transaction; | |
import org.hibernate.boot.Metadata; | |
import org.hibernate.boot.MetadataSources; | |
import org.hibernate.boot.registry.StandardServiceRegistry; | |
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; | |
import dao.interfaces.DatabaseInterface; | |
public class DatabaseInit implements DatabaseInterface { | |
private StandardServiceRegistry standardServiceRegistry; | |
private Metadata metadata; | |
private static SessionFactory sessionFactory; | |
private Session session; | |
private Transaction transaction; | |
public DatabaseInit() { | |
initConnection(); | |
} | |
@Override | |
public void initConnection() { | |
if (sessionFactory == null) { | |
this.standardServiceRegistry = new StandardServiceRegistryBuilder().configure(DatabaseInterface.HIBERNATE_CONFIG).build(); | |
this.metadata = new MetadataSources(this.standardServiceRegistry).getMetadataBuilder().build(); | |
sessionFactory = metadata.getSessionFactoryBuilder().build(); | |
} | |
} | |
@Override | |
public Session openConnection() { | |
try { | |
if (this.session == null || !this.session.isOpen()) { | |
this.session = sessionFactory.openSession(); | |
this.transaction = session.beginTransaction(); | |
} | |
} catch (HibernateException e) { | |
e.printStackTrace(); | |
} | |
return this.session; | |
} | |
@Override | |
public void processConnection() { | |
try { | |
openConnection(); | |
this.transaction.commit(); | |
} catch (HibernateException e) { | |
if (this.transaction != null) { | |
this.transaction.rollback(); | |
} | |
e.printStackTrace(); | |
} finally { | |
closeConnection(); | |
} | |
} | |
@Override | |
public void closeConnection() { | |
this.session.close(); | |
} | |
} |
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 dao.interfaces; | |
import org.hibernate.Session; | |
public interface DatabaseInterface { | |
String HIBERNATE_CONFIG = "hibernate.cfg.xml"; | |
void initConnection(); | |
Session openConnection(); | |
void processConnection(); | |
void closeConnection(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment