Reputation: 307
This is the command to display information data sheet, I see the declaration it is repeated
CODE 1
public class DBTable {
public List<MdGmail> showGmail() {
Configuration conf = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = conf.buildSessionFactory();
currentSession = sf.getCurrentSession();
currentSession.beginTransaction();
return currentSession.createCriteria(MdGmail.class).list();
}
public List<MdBlogger> showBlogger() {
Configuration conf = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = conf.buildSessionFactory();
currentSession = sf.getCurrentSession();
currentSession.beginTransaction();
return currentSession.createCriteria(MdBlogger.class).list();
}
}
In my class DBTable,I create a list function to display data table in a database as table gmail,order... With the first code 1 need to rewrite the declaration for each function, so what I want is to create a connection function for all with code 2
But with the way this declaration it will not update the value was changed in the database
CODE 2
public class DBTable {
private static final Configuration conf = new Configuration().configure("hibernate.cfg.xml");
private static final SessionFactory sf = conf.buildSessionFactory();
private static Session currentSession;
public DBTable() {
currentSession = sf.getCurrentSession();
currentSession.beginTransaction();
}
private static DBTable instance = null;
public static DBTable getInstance() {
if (instance == null) {
instance = new DBTable();
}
return instance;
}
public List<MdGmail> showTableGmail() {
return currentSession.createCriteria(MdGmail.class).list();
}
public List<MdGmail> showTableOrder() {
return currentSession.createCriteria(MdGmail.class).list();
}
}
And if use new additional data function, the connection will be closed and command data showing that my table would stop working.Please help me
public boolean saveOrUpdateGmail(MdGmail table) {
try {
currentSession.saveOrUpdate(table);
currentSession.getTransaction().commit();
return true;
} catch (Exception e) {
currentSession.getTransaction().rollback();
e.printStackTrace();
return false;
}
}
Upvotes: 0
Views: 65
Reputation: 19956
The simplest strategy of using Hibernate is open a session (or get current one), begin a transaction, do request, commit, and close a session for every operation (showTableGmail, saveOrUpdateGmail
). So you need to delete all code from DBTable()
constructor and do something like this.
Upvotes: 1