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

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)

Related

Hibernate session.update/session.delete does not work

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.

spring data i want to use hibernate query

i write class to fetch data using hibernate query. when i get Session from EntityManager using
Session session=null;
sessionFactory=entityManager.unwrap(SessionFactory.class);
session=(Session) sessionFactory.getCurrentSession();
or
Session session = (Session) entityManager.getDelegate();
and session agin asking cast the session into EntityManager
public class BranchCustomRepositoryImpl implements BranchCustomRepository{
#PersistenceContext
private EntityManager entityManager;
private SessionFactory sessionFactory;
public Branch findByOrgOrgIdAndBranchId(String orgId, String branchId) {
//Session session=null;
//sessionFactory=entityManager.unwrap(SessionFactory.class);
//session=(Session) sessionFactory.getCurrentSession();
Session session = (Session) entityManager.getDelegate();
System.out.println("BranchCustomRepositoryImpl");
Long orgId2=Long.valueOf(orgId);
Long branchId2=Long.valueOf(branchId);
try{
Query query= (Query)((EntityManager) session).createQuery("from Branch b where b.org.orgId=:orgId AND b.branchId=:branchId");
query.setParameter("orgId", orgId2);
query.setParameter("branchId", branchId2);
return (Branch) query.uniqueResult();
}catch(Exception e){
System.out.println("Exception"+e.toString());
}finally{
try {
if(session!=null){
session.close();
System.out.println("session closed");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
it getting error like,
java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Long (n/a)]
if any one know how to use hibernate query in spring data jpa please help me
Since the type of persistent attribute orgId2 is Long, the corresponding
type argument should also be Long while creating the ParameterExpression. And consequently, because type of the ParameterExpression is Long, type of the parameter's value should also be Long as well. So do the following change when you setting query parameters.
Instead of your current lines such as below
query.setParameter("orgId", orgId2);
query.setParameter("branchId", branchId2);
Change it like below
query.setParameter("orgId", Long.valueOf(orgId2));
query.setParameter("branchId", Long.valueOf(branchId2));

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>

Hibernate table update error

My web application used hibernate mysql. I can add records to database without having any issue. But if i going to update latest adding record It will not updating. But if I re-start the server(tomcat) and then try to update It's working.
To update the record following condition should be satisfied.
//Check record aready exist
public boolean idExists(String id) {
Session session = (Session) HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Officer> list = (List<Officer>) session.createQuery("from Officer as p where p.idno =" + "\'" + id.trim() + "\'").list();
return (list.size() > 0) ;
}
Immediate(return 1) adding records It will returns 0. But one restart the server and update the record It will work. I also verify after adding record it's successfully commit to DB.
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Let me know if something wrong in my code?
Hibernate does not interact with database immediately after transaction or it does at the time of flushing session, it manages and updates its record to increase system performance in its own way, If you want immediate reflection use :
session.flush();
After updating records.
You could try to flush the session. Entities are not immediately persisted into the database.
session.flush();
I think better you use Transactions here.
You put session.biginTranasaction();
Instead do something like,
public boolean idExists(String id) {
Session session = (Session) HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
List<Officer> list = (List<Officer>) session.createQuery("from Officer as p where p.idno =" + "\'" + id.trim() + "\'").list();
tx.commit();
if(session != null){
session.close();
}
return (list.size() > 0) ;
}
On other end you should generate new session and do other stuffs.

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