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));
Related
I am using hibernate in my automation testing project, to execute a database 'clean-up routine' that is:
disabling constraints for all tables in the database
removing records by ID's that I stored when creating records used for my automation testing
enabling constraints for all tables in the database
Here is my pseudo code:
private SessionFactory sessionFactory;
private void initialize()
{
try
{
Configuration config = createHibernateConfiguration();
addAnnotatedClassesForClientDB(config);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(config.getProperties());
serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = config.buildSessionFactory(serviceRegistry);
}
catch (HibernateException e)
{
logger.error("Problem creating session factory!");
e.printStackTrace();
}
}
public Session openSession()
{
Session session = sessionFactory.openSession();
session.beginTransaction();
return session;
}
public void cleanClientDatabase()
{
Session session = openSession();
try
{
logger.info("Client DB cleaning started...");
String combinedQuery = // her comes my SQL query
Query query = session.createNativeQuery(combinedQuery);
query.executeUpdate();
closeSession(session);
}
catch (Exception e)
{
logger.error("Failed cleaning Client DB! " + e.getClass().getSimpleName());
e.printStackTrace();
session.getTransaction().rollback();
session.close();
}
}
Now from time to time, it sticks at query.executeUpdate(); in cleanClientDatabase() method and will hang there forever, until I manually kill transaction in Microsoft SQL Management studio by PID.
For some reason an exception is never thrown so I can't tell what is the error, I suspect some sort of lock, what can I do to avoid this issue and fix my code?
Thank you.
I want to know if it's possible to create custom query for liferay default table like user, userGroup...
I looked at the example but they give examples that on the custom tables (guestbook table)
try this code
public List<User> getUserByRecentChat(long userId){
Session session=null;
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
try {
session = sessionFactory.openSession();
String sql = CustomSQLUtil.get(getClass(), "getUserByRecentChat");
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setCacheable(false);
sqlQuery.addEntity("users_", UserImpl.class); // for user table
QueryPos pos = QueryPos.getInstance(sqlQuery);
pos.add(userId);
pos.add(userId);
return (List<User>) sqlQuery.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
sessionFactory.closeSession(session);
}
return null;
}
Yes you can use Custom Query for Liferay Default Tables
Thanks
on my dao i have two queries. if the first query is successfully committed then second query should run.but if the first query is committed but second query somehow failed to commit/got some exception then the first query which is committed should also be rolled back. how can i do it?
#Repository
public class UpdatePaymentImpl implements UpdatePayment {
#Autowired
SessionFactory sessionFactory;
Session session;
Transaction trans;
#Override
public int updatePayment(#RequestBody UpdateParam updateParam) {
String totalFee=updateParam.getTotalFee();
// float amountPaid=Float.toString(updateParam.getAmountPaid());
String amountPaid=Double.toString(updateParam.getAmountPaid());
//System.out.println(amountPaid);
String depositSlioNo=updateParam.getDepositSlipNo();
String masterId= updateParam.getMasterId();
String advCode=updateParam.getAdvCode();
try{
session=sessionFactory.openSession();
trans=session.beginTransaction();
Query query= session.createQuery
("update CandidateappearagainstadvtcodeEntity cd set cd.paymentstatus='Completed',
cd.amountpaid=:depoFee,cd.challanid=:depositSlip where
cd.studentmasterid=:masterid and cd.advertisementcode=:advCode");
System.out.println(updateParam.getAdvCode());
query.setParameter("depoFee",amountPaid);
query.setParameter("depositSlip",depositSlioNo);
query.setParameter("masterid",masterId);
query.setParameter("advCode",advCode);
int result= query.executeUpdate();
trans.commit();
System.out.println("update successful");
if(result>0){
String masterId1= updateParam.getMasterId();
String advCode1=updateParam.getAdvCode();
Double amountpaid1=updateParam.getAmountPaid();
session = sessionFactory.openSession();
trans = session.beginTransaction();
Query query1 =session.createQuery(" update CandidateappeartoadvtnumberEntity
cnd set cnd.paymentstatus='Completed', cnd.depositedfee=:depofee where
cnd.studentmasterid=:masterid
and cnd.advertisementcode=:advcode");
query1.setParameter("depofee",amountpaid1);
query1.setParameter("masterid",masterId1);
query1.setParameter("advcode",advCode1);
int result1 = query1.executeUpdate();
trans.commit();
System.out.println("updated");
}
return result;
}catch (Exception e){
System.out.println("update error " +e);
trans.rollback();
return 0;
}finally {
session.close();
}
}
}
looks like you creating two different sessions and has separate commit operation.
To reach your goals you have to open one session and one transaction, then execute both queries and only after successful execution do commit.
In that case if any on query execution will fail you won't affect database state. Currently you already commit first query so if your second query will fail the changes from previous query won't be reverted.
Here is an example.
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)
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.