In my project I get "could not insert the table error", I'm adding necesarry code parts to here and hope for the best :)
My LogIn Class
package DAO;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.AnnotationConfiguration;
import tables.Users;
public class LogIn {
Session session;
public boolean RegisterUsers(Object user) {
if (SaveDatabase(user)) {
return true;
} else {
return false;
}
}
public boolean GetUsersWithId(Users user) {
SessionFactory sessionfactory = new Configuration().configure()
.buildSessionFactory();
session = sessionfactory.openSession();
user = (Users) session.get(Users.class, user.getUserId());
session.close();
if (user == null) {
return false;
} else {
return true;
}
}
public boolean SaveDatabase(Object object) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long courseId = null;
try {
transaction = session.beginTransaction();
session.save(object);
courseId = (Long) session.save(object);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
System.out.println(e.getMessage());
return false;
}
} finally {
session.close();
}
return true;
}
}
HibernateUtil
package DAO;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Test class for these codes
import DAO.LogIn;
import tables.Location;
import tables.Users;
public class Test {
public static void main(String[] args) {
// Test RegisterUser and GetUsersWithId in here
LogIn test = new LogIn();
Users user = new Users();
user.setUserEmail("email");
user.setUserAdress("adres here");
user.setUserFbId(3);
test.RegisterUsers(user);
}
}
Thanks for help
Edit: Removed config. xml files and auto-created Users class to clean up the mess.
You have a field named session
, and a local variable also named session
. You open a Hibernate session and assign it to the local variable, but you close the field and not the local variable.
Remove the session
field. You shouldn't store a Hibernate Session in a field like that. It doesn't make sense. You'll then get a compilation error that you'll need to fix by declaring the session local variable in a larger scope (outside of the try block).