Hibernate syntax error : Expected DOT - java

I am getting the following error on the execution of the below hibernate transaction : expecting DOT, found '=' near line 1, column 32 [update t_credential set status = :status , assigned_engine = :engine where id = :id] .
Also, t_credential is a table and not an object. Does hibernate allow to use this way or does it compulsorily have to be an object?
for(Credential credential: accountList){
Query query = ssn.createQuery("update t_credential set status =:status , assigned_engine = :engine where id = :id");
query.setParameter("status", status);
query.setParameter("engine", assignedTo);
query.setParameter("id", String.valueOf(credential.getId()));
int result = query.executeUpate();
}

Look at the HQL example here: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html#batch-direct. It seems that you need to refer to an object: "update t_credential c", and then update it's fields, like this: "set c.status = :status" and so on.

If you want to use Hibernate with SQL Query (and not HQL query), you may have to use a different function.
ssn.createSQLQuery(" ... ");
I never used this function, so I hope it's a good answer for you.
Max

Related

Why does JPA give me a syntax error at or near?

I am learning spring-boot and I have a connection to a database, I am trying to perform the following query.
#Query(value = "select f.entity_id as 'NIT' from renting.fine f where f.companyparent = :companyParent", nativeQuery = true)
But it generates the following error about the value that starts with a single quote, I can't get it to recognize the value
org.postgresql.util.PSQLException: ERROR: syntax error at or near "'NIT'"
Remove single quotes around 'NIT'. In order to define aliases for column you don't require quotes at all.
#Query(value = "select f.entity_id as NIT from renting.fine f where f.companyparent = :companyParent", nativeQuery = true)
This should work.

Creating dynamic query using jpa criteria

I created dynamic query using jpa criteria but an extra pair of parentheses gets added to columns to be selected when I do userGroupSubquery.select(userGroupsRoot);
generated query
select (securitygr3_.group_name, securitygr3_.user_name) from gm.security_groupings securitygr3_ where 1=1 and securitygr3_.user_name='xxx' and (securitygr3_.group_name in ('XYZ'))
expected query:
select securitygr3_.group_name, securitygr3_.user_name from gm.security_groupings securitygr3_ where 1=1 and securitygr3_.user_name='xxx' and (securitygr3_.group_name in ('XYZ'))
Subquery<SecurityGroupings> userGroupSubquery = secUsersQuery.subquery(SecurityGroupings.class);
Root<SecurityGroupings> userGroupsRoot = userGroupSubquery.from(SecurityGroupings.class);
Path<SecurityGroupingsId> secGroupId = userGroupsRoot.get("id");
Path<SecurityUsers> secUsers = secGroupId.get("securityUsers_1");
Path<SecurityUsers> securityUsers = secGroupId.get("securityUsers");
Path<String> su_name = secUsers.get("name");
Path<String> name = securityUsers.get("name");
userGroupSubquery.select(userGroupsRoot);
userGroupSubquery.getCompoundSelectionItems();
//userGroupSubquery.where(criteriaBuilder.equal(pet.get(SecurityGroupingsId_.id), root.<String>get("name")));
Predicate restrictions3 = criteriaBuilder.conjunction();
restrictions3 = criteriaBuilder.and(restrictions3, criteriaBuilder.and(criteriaBuilder.equal(su_name, dto.getUserId().trim().toUpperCase())));
restrictions3 = criteriaBuilder.and(restrictions3, criteriaBuilder.and(name.in(userGroups)));
userGroupSubquery.where(restrictions3);
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(userGroupSubquery));
}
secUsersQuery.where(restrictions);
Its just that I get an extra pair of parentheses at select (securitygr3_.group_name, securitygr3_.user_name) from
which gives me ora-00907 missing right parenthesis error. I am sure it is coming from userGroupSubquery.select(userGroupsRoot) but I am not sure why. Please help
I got the solution for the above. When the entity has a composite key, then in JPA criteria instead of doing
userGroupSubquery.select(userGroupsRoot);
we should do
userGroupSubquery.select(userGroupsRoot.get("id"));
where id is the composite id.

Hibernate Restrictions subquery with id of main query

I got 2 Tables with data
Main
---
id // 1
Second
---
id //1; 2
property //"a"; "b"
creationDate(DD/MM/YYYY) //01/01/2000; 02/02/2002
mainId // 1; 1
The connection is 1-*
So, what I want to do is to query my "Main" table by the property in "Second", but I want to search only the newest property.
So searching "a" must not give any result, as "b" is a newer data.
I wrota it via SQL and it looks like this:
select distinct m.id from Main m join Second s on m.id = s.mainId where s.property = 'b' and s.creationDate = (SELECT MAX(s2.creationDate) from Second s2 where s2.mainId = m.id);
I figured out some java code, but I have no idea how to use this s2.mainId = m.id part via Restrictions:
DetachedCriteria d = DetachedCriteria.forClass(Second.class, "s1");
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("s1.creationDate"));
d.setProjection(proj).add(Restrictions.eq("WHAT COMES HERE");
Or maybe should I use defferent approach?
Unformtunately I need to use Hibernate Criterion Interface as whole seach mechanismus is written via Criterion.
DetachedCriteria innerCrit = DetachedCriteria.forClass(Second.class);
innerCrit.setProjection(Projections.max("creationDate");
innerCrit.add(Restrictions.eqProperty("id", "main.id"));
DetachedCriteriaouterCrit outerCrit = DetachedCriteria.forClass(Main.class, "main");
outerCrit.createAlias("second", "second");
outerCrit.add(Subqueries.eq(second.creationDate, innerCrit));
outerCrit.add(Restrictions.eq("second.property", "b"));
This outerCrit will get you the Main object.

Encountered "INSERT" at character 1, but expected: ["DELETE", "SELECT", "UPDATE"]

I have an insert JPA named query as below. When I try to execute it from my DAO using enity manger I am getting the below error. I am using Apache OpenJPA, I could not identify the root cause of this issue. I cannot use the persist method because of the complexity of my domain object.
Encountered "INSERT" at character 1, but expected: ["DELETE", "SELECT", "UPDATE"].
#NamedQuery(
name=IuaPersistenceConstants.QUERY_INSERT_AGREEMENT_ACKNOWLEDGEMENT,
query="INSERT INTO AgreementAcknowledgement agrackn VALUES agrackn.id.agrmntCntntUrl = :agrmntCntntUrl, agrackn.id.prvsndUserSqn = :prvsndUserSqn, agrackn.id.prvsnUserEffD = :userEffDate, " +
"agrackn.id.agrmntacknEffD = :agrmntacknEffD, agrackn.acknExpD = :acknExpD, agrackn.crtTs = :crtTs, agrackn.crtUidC = :crtUidC, agrackn.lstUpdtTs = :lstUpdtTs, agrackn.lstUpdtUidC = :lstUpdtUidC")
Query ackQuery =getEntityManager().createNamedQuery(IuaPersistenceConstants.QUERY_INSERT_AGREEMENT_ACKNOWLEDGEMENT);
ackQuery.setParameter("agrmntCntntUrl", agreementDO.getAgreementURL());
ackQuery.setParameter("agrmntacknEffD", agreementDO.getAgreementEffDate());
ackQuery.setParameter("acknExpD", agreementDO.getAgreementExpDate());
ackQuery.setParameter("prvsndUserSqn", userDO.getUserSequence());
ackQuery.setParameter("userEffDate", userDO.getUserEffDate());
ackQuery.setParameter("crtTs", new Date());
ackQuery.setParameter("crtUidC", "WS");
ackQuery.setParameter("lstUpdtTs", new Date());
ackQuery.setParameter("lstUpdtUidC", "WS");
ackQuery.executeUpdate();
OpenJPA doesn't seem to support JPQL "INSERT" queries. But then that is not surprising since JPA DOES NOT define INSERT queries. It defines SELECT, UPDATE, DELETE queries and that is all. See the JPA spec. This is not SQL.

How to pass parameter on jpa query?

I have two entities Like SmsOut and SmsIn. The relation between two entities contains OneToMany where smsIn.id is primary key and smsOut.sms_in_id is foreign key.
Now I want to pass parameter like smsIn.mobileNumber, smsIn.smsText and so on, on the query
SELECT so FROM SmsOut so order by id desc
Following is my database diagram:
Edited
Following is my code :
String sql = "SELECT so FROM SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc";
Query query = em.createQuery(sql);
query.setParameter("mobileNumber", mobileNumber);
query.setParameter("smsText", smsText);
query.setParameter("shortCode", shortCode);
query.setParameter("smsOutDate", startDate);
query.setParameter("smsOutDate", endDate);
smsOutList = query.getResultList();
and exception is :
SEVERE: line 1:188: expecting "and", found '='
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: expecting "and", found '=' near line 1, column 188 [SELECT so FROM com.f1soft.SMSC.entities.SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:96)
Please Help me.
Thanks
You haven't explained the JPA relationship between SmsIn and SmsOut, so I'll assume SmsOut has a getSmsIn() with a relation on the id field.
When you have an EntityManager em, you can call em.createQuery, which is like SQL prepare, and then setParameter:
TypedQuery<SmsOut> q = em.createQuery("SELECT so FROM SmsOut so WHERE so.smsIn.mobileNumber = :number ORDER BY id DESC");
q.setParameter("number", "12345678");
List<SmsOut> results = q.getResultList();
See the Javadoc for Query for the different ways you can specify the parameters.
SELECT so FROM SmsOut so WHERE smsIn.mobileNumber = ? AND smsIn.smsText =? order by id desc
Replace the ? sign with the apropiate values.
between is the problem:
between so.smsOutDate =:startDate and so.smsOutDate =:endDate
try
so.smsOutDate between =:startDate and =:endDate

Categories

Resources