Hibernate session.update/session.delete does not work - java

code:
public void test() {
Session session = sessionFactory.openSession();
User u = new User();
u.setUsername("user1");
session.delete(u);
session.close();
}
I want to know why deletion does not work

try before session.close()
session.flush()

You are trying to delete non-managed entity that is not attached to session. In order to manipulate entity you should first attach it to session:
User u = (User) session.get(User.class, 1L);
session.delete(u);
Above is this sample of loading by id, so if you are restricted to username you have to write a more complex query.

Related

Hibernate adding new element #oneToMany

what's wrong guys I have that relations in hibernate #oneToMany:
This is in loan class:
#ManyToOne(cascade=CascadeType.ALL)
private users user;
This is in user class:
#OneToMany(mappedBy="user",fetch=FetchType.LAZY)
private Set<loans> loans=new HashSet<loans>(0);
here I have method to insert new loan:
public static void addLoanToUser(Integer userID,String brand,String model,String registration,String loanStart , String loanEnd){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
users user = (users) session.load(users.class, userID);
Set<loans> loanSet = new HashSet();
loans loan = new loans();
loan.setBrand(brand);
loan.setModel(model);
loan.setRegistration(registration);
loan.setLoanStart(loanStart);
loan.setLoanEnd(loanEnd);
loan.setPaydone("no");
loanSet.add(loan);
user.setLoans(loanSet);
session.saveOrUpdate(user);
session.save(loan);
session.getTransaction().commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
When I insert data to the database there is always NULL on Foreign Key.
I tried to find sth on the stack but nothing helped.
Its because you have to set relation on "key holder" in your case that is loan entity. So
users user = (users) session.load(users.class, userID);
loans loan = new loans();
..... setup
loan.setUser(user)
session.saveOrUpdate(user);
And you do realize, that if user will take new loan, you effectively removes other loans of that user (in current session) by setting brand new user.loans set ? :) I wish banking systems work like that :)

org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.nextTimestamp

Please Help:
Below error when I tried to add details to tables using hibernate:
NullPointerException
org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.nextTimestamp(RegionFactoryCacheProviderBridge.java:93)
SessionFactoryImpl.openSession(SessionFactoryImpl.java:639)
SessionFactoryImpl.openSession(SessionFactoryImpl.java:648)
com.package1.service.AuthenticateUser.addUser(AuthenticateUser.java:32)
com.package1.controllers.LoginServlet.doPost(LoginServlet.java:68)
AuthenticateUser:
public class AuthenticateUser {
public void addUser(String uname, String uemail, String usrnme,
String upass) {
Session session = factory.openSession(); //Line No:32
Transaction txn = session.beginTransaction();
user.setName(uname);
user.setEmail(uemail);
user.setUsrname(usrnme);
user.setPassword(upass);
txn.commit();
session.save(user);
session.close();
factory.close();
}
private static SessionFactory factory = HibernateSessionManager
.getSessionFactory();
private User user = new User();
}
In LoginServlet I call
authenticateUser.addUser("abcdef", "abcdef","abcdef", "abcdef");
You are closing the factory object, so attempting to open a session with it has chances to cause such a crash (on next call).
Remove this line :
factory.close();
Try to convert this order:
txn.commit();
session.save(user);
Like this:
session.save(user);
txn.commit();
this error ocurrs when you try to create an EntityManager with a closed EntityManagerFactory.
So, the recomandation is,
EntityManagers must be ephimerals *create and close only in the scope of the transaction.
EntityManagerFactory must be application scoped.
NullPointerException
org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.nextTimestamp(RegionFactoryCacheProviderBridge.java:93)

org.hibernate.SessionException: Session is closed

public List<Examination> loadExaminations(int pID) {
session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
ManagedSessionContext.bind(session);
session.beginTransaction();
Patient tpatient = (Patient) session.get(Patient.class, pID);
List<Examination> examinations = new LinkedList<>();
if (tpatient.getExaminations()!=null)
if (!tpatient.getExaminations().isEmpty()) { //I get the exception to this line
examinations = (List<Examination>) tpatient.getExaminations();
}
ManagedSessionContext.unbind(sessionFactory);
session.flush();
session.getTransaction().commit();
session.close();
return examinations;
}
Exception:
org.hibernate.SessionException: Session is closed
I get the exception, but actually in the program it seems to be fine; everithing is happening as it should, but the exception is bothering me.
Thanks for the help!
If written into your Hibernate Config file session close tag then no need to use session.close() method otherwise written session close tag into hibernate config file and remove session.close() statement.
Like following line written into hibernate config file.
<property name='transaction.auto_close_session'>true</property>

Spring Hibernate getCurrentSession() delete not working

I am fully testing an entity on my unit test, and almost everything worked so far: create, update, list. However, when I try to delete a record, it is not getting deleted. Here is the code I am using:
public void delete (Integer id) {
// This doesnt work even though I know user is set and id is not null
User user = find(id);
getSession().delete(user);
// This will work
// Query query = getSession().createSQLQuery("DELETE FROM users WHERE id = " + id);
// query.executeUpdate();
}
private Session getSession() {
if (session == null) {
try {
session = SessionFactoryUtils.getSession(sessionFactory, Boolean.TRUE);
TransactionSynchronizationManager.bindResource(session.getSessionFactory(), new SessionHolder(session));
} catch (Exception e) {
session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
}
}
return session;
}
If I execute the query directly it works but using the delete() method doesnt. I think it may be related to committing the transaction but I already tried something like that and no luck. Any ideas?
I found the problem with this one.
First, find() method was evicting my user model, and probably taking it out of the session.
After delete(), I also needed to session.flush()

hibernate Open Session in View

i am using the following approach to sole lazy initialization problem in hibernate.Pleas tell me whether it will work or not .
I have to implement my transcation in my persistance layer compulsary due to some reasons.
public class CourseDAO {
Session session = null;
public CourseDAO()
{
this.session = this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public Course findByID(int cid){
Course crc = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery("from Course as course where course.cid = "+cid+" ");
crc = (Course) q.uniqueResult();
//note that i am not commiting my transcation here.Because If i do that i will not be able to
//do lazy fetch
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
return crc;
}
}
and in the filter i am using the folling code
session = HibernateUtil.getSessionFactory().getCurrentSession();
if(session.isOpen())
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
IS this approach right??
Can it can have any problem
could you explain why do you need to have ur transactions in ur repositories? the problem there is that they are going to be so fine-grained, so you are not gonna get any advantage from the session caching
then you are opening the transaction there but closing it in your filter. what happens if you access multiple repositories in your service? Maybe i am not understanding what you mean but i think you need to re-think the reasons that force you to manage your transactions in your repositories
When do you create you CourseDAO? If it is a singleton bean or something else that lives longer than a page view, it will need to keep a SessionFactory and generate a new Session when it needs one rather than keeping a Session.

Categories

Resources