JPA query with SELECT CASE WHEN - spring-mvc

Have a query like this,
select *
from job_profile
where case
when exists (
select 1
from job_profile
where screening_type_id = 2 and job_category_id = 4
)
then screening_type_id = 2 and job_category_id = 4
else screening_type_id =4
end;
which I need to write this in JPA.
String GET_JOB_VACCINATIONS_BY_JOB_CAT_ID_AND_SCRN_TYPE_ID = "SELECT jobvacc FROM JobVaccination jobvacc WHERE CASE"
+ " WHEN EXISTS ( SELECT 1 FROM JobVaccination jobvacc2 WHERE jobvacc2.jobCategoryMast.jobCategoryId=:jobCategoryId AND jobvacc2.screeningTypeMast.screeningTypeId=:screeningTypeId )"
+ " THEN jobvacc.jobCategoryMast.jobCategoryId=4 AND jobvacc.screeningTypeMast.screeningTypeId=2 "
+ " ELSE jobvacc.screeningTypeMast.screeningTypeId=2"
+ " END";
Tried this way which throws exception like "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: = near line 1, column 260 [SELECT............."
Cant we write the case queries in JPA ?
Refereed this link https://en.wikibooks.org/wiki/Java_Persistence/JPQL_BNF#New_in_JPA_2.0 which says yes.

Related

How to find value in a set in SQLite [duplicate]

In Mysql, FIND_IN_SET is used to find value in a set. I have tried FIND_IN_SET in SQLite, but it is not an SQL keyword. I have Googled, but I did not get an answer. If anybody knows, please tell me the alternative to FIND_IN_SET in SQLite.
If you need just a true / false value rather than index then you can use LIKE clause:
(',' || column_name || ',') LIKE '%,value,%'
we can write query like change into hibernate critearea
my old query
select * FROM game_detail WHERE content_id=176 and FIND_IN_SET(12,group_master_id)
New query
select *
FROM game_detail
WHERE content_id=176
and (group_master_id LIKE '%12,%'|| group_master_id LIKE '%,12,'|| group_master_id LIKE '%12')
This is my old query
String query = "SELECT a.content_id,a.content_name,a.image_name,a.image_path,a.rating,d.content_type_name"
+ "from content_master a, category_content_mapping b, "
+ "game_detail c, content_type_master d "
+ "where a.content_id=b.content_id "
+ "and c.content_id = a.content_id "
+ "and a.content_type_id = d.content_type_id "
+ "and b.category_id = '" + category_id + "' "
+ "and find_in_set('" + group_master_id + "',c.group_master_id) "
+ "and a.is_active='Y' and b.is_active = 'Y' and c.is_active = 'Y'"
+ "order by b.content_mapping_id DESC limit 0,3";
Criteria in hibernate use like alternate of find_in_set
Session session=new Configuration().configure().buildSessionFactory().openSession();
Criteria criteria=session.createCriteria(ContentMaster.class);
criteria.setFetchMode("CategoryContentMapping", FetchMode.JOIN);
criteria.setFetchMode("GameDetail", FetchMode.JOIN);
criteria.createAlias("categoryContentMappings","cat");
criteria.createAlias("contentTypeMaster", "ctm");
criteria.createAlias("gameDetails","game");
criteria.add(Restrictions.eq("cat.categoryMaster.categoryMasterId", 9));
criteria.add(Restrictions.disjunction()
.add(Restrictions.like("game.groupMasterId","%12,%"))
.add(Restrictions.like("game.groupMasterId","%,12,%"))
.add(Restrictions.like("game.groupMasterId","%12%")));
criteria.add(Restrictions.eq("isActive", "y"));
criteria.add(Restrictions.eq("cat.isActive", "y"));
criteria.add(Restrictions.eq("ctm.isActive", "y"));
criteria.addOrder(Order.desc("cat.contentMappingId"));

SQLiteException: near "t": syntax error (code 1):

I'm receiving the following error from my insert db call.
"android.database.sqlite.SQLiteException: near "t": syntax error (code 1): , while compiling: INSERT INTO OCR(bmp, title, description) VALUES ('[B#9430d52', 'Result:', '
pacifism
Enchant creature
Creature can't attack Or
That
—Knrtce of Qal Sima
');
This is my insert statement
String INSERT_TO_DB = "INSERT INTO " + TABLE_NAME + " ("+
COLUMN_BITMAP + ", " +
COLUMN_TITLE + ", " +
COLUMN_DESCRIPTION +") " +
"VALUES ('" + getBytes(ocr.getBitmap()) + "', '" + ocr.getTitle() + "', '" + ocr.getDescription() + "');";
db.execSQL(INSERT_TO_DB);
The thing is it was working on other images, i'm thinking it has something to do with the fact that there's a lot of "/n" in the description it's trying to insert into the db.
Never put string values directly into an SQL statement; use parameters instead.
It is not necessary to use a prepared statement object to achieve this:
db.execSQL("INSERT ... VALUES(?, ?, ?)",
new Object[]{ ocr.getTitle(), ... });
And there is a helper function that constructs the statement for you, and handles binary data correctly:
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE, ocr.getTitle());
cv.put(COLUMN_BITMAP, ocr.getBitmap()); // byte array
...
db.insert(TABLE_NAME, null, cv);

Stored Procedures and asp.net programmability; variable or SQL

Trying to display a users Lastname, Firstname --- Website
And I need to insert a comma and space after Lastname to a GridView.
I am trying to add a CASE statement in SQL and having trouble figuring it out.
Perhaps I need to use #parameter (scalar variable?) to abstract the
memory read from CASE statement; or my syntax is wrong and I just don't
understand.
SELECT
CASE
WHEN IsNull(people_Table.firstName, '') = ''
THEN CONCAT(people_Table.lastName, ', ', people_Table.firstName)
ELSE people_Table.lastName
END as fullName,
people_Table.website
FROM
people_Table
INNER JOIN
membership_Table on people_Table.ID = membership_Table.personID
WHERE
rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY
people_Table.lastName
Getting SQL Server error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'people_Table'.
Otherwise I suppose I should use an asp databoundevent in the template.
What is better for performance and security?
SELECT ISNULL(people_Table.lastName + ', ', '')
+ ISNULL(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName
OR
SELECT COALESCE(people_Table.lastName + ', ', '')
+ COALESCE(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName

using placeholder in sql query in asp.net

I am an ASP.Net developer & using sql server CE 4.0 I want to know how to use place holder for this code, As this query is currently vulnerable to sql injection. Place holder can prevent this but the problem is for example query = "SELECT * FROM TABLE WHERE TITLE = #0" but in my query the value of #0 is dynamically added to query how do i use place holder
this is the code
if (Request["search"] != "" && Request["search"] != null)
{
var search = Request["search"].Trim();
string[] querynew = search.Split(' ');
var searchquery = "and ";
foreach (string word in querynew)
{
searchquery += "response_table.adtitle LIKE '%" + word + "%' OR ";
}
sql += searchquery.Remove(searchquery.Length - 4);
}
if (Request["min"] != "" && Request["min"] != null && Request["max"] != null && Request["max"] != "")
{
sql = sql + " and (CAST(response_table.price AS Float)) between " + Request["min"].Trim() + " AND " + Request["max"].Trim();
}
// 3. the order clause
switch (Request["sort"])
{
case "recent":
sql = sql + "ORDER BY response_table.response_ID DESC OFFSET " + offset + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY";
break;
case "hightolow":
sql = sql + "ORDER BY CAST(response_table.price AS Float) Desc OFFSET " + offset + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY";
break;
case "lowtohigh":
sql = sql + "ORDER BY CAST(response_table.price AS Float) ASC OFFSET " + offset + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY";
break;
default:
break;
}
result = db.Query(sql);
Thank You
Using parameters (instead of concatenating strings) allows you to optimize performance of your queries.
You can use a SqlCeCommand. It has a collection of parameters and you can find a sample here regarding how to use them.

Python: infinite loop while executing SQLite statement

I have this 2 SQLite scripts:
both tested by direct input into SQLite.
def getOutgoingLinks(self, hostname):
t = (hostname,)
result = self.__cursor.execute("SELECT url.id, hostname.name, url.path, linking_to.keyword, siteId.id " +
"FROM url, hostname, linking_to, " +
"(SELECT url.id FROM url, hostname " +
"WHERE hostname.name = (?) " +
"AND hostname.id = url.hostname_id " +
") AS siteId " +
"WHERE linking_to.from_id = siteId.id " +
"AND linking_to.to_id = url.id " +
"AND url.hostname_id = hostname.id", t)
result = result.fetchall()
return result
def getIncommingLinks(self, hostname):
t = (hostname,)
result = self.__cursor.execute("SELECT url.id, hostname.name, url.path, linking_to.keyword, siteId.id " +
"FROM url, hostname, linking_to, " +
"(SELECT url.id FROM url, hostname " +
"WHERE hostname.name = (?) " +
"AND hostname.id = url.hostname_id " +
") AS siteId " +
"WHERE linking_to.to_id = siteId.id " +
"AND linking_to.from_id = url.id " +
"AND url.hostname_id = hostname.id", t)
result = result.fetchall()
return result
The getIncommingLinks() methond works very well, but getOutgoingLinks() causes an infinite Loop when python trys to execute the SQL statement. Any ideas what went wrong?
Rewrite your Select statements without select ...( Select ...) - thats very bad style. The result may solve your problem.
If by infinite loop you mean that the function doesnt ever get to return a value, I had the same problem.
Found the solution in Why python+sqlite3 is extremely slow?. With large tables it becomes a performance issue with the version shipped with python 2.7. I solved it by upgrading sqlite3 as specified here: https://stackoverflow.com/a/3341117/3894804

Resources