HQL query returing null value on use of like operator for search - hql

query = genericDAOImpl.getHibernateSession().createQuery("select t from ticket t where createdBy=:user and t.subject like concat("%", :summary, "%")
.setParameter("user", userId)
.setParameter("summary", inputBean.getSummary);
this is my query when I search for some values it returns the proper output but when I give null value for the search field it returns empty list actually it should return all the values when the search field is empty

You should just use a plain named placeholder for the predicate of the LIKE expression, and then bind the wildcard string from the Java side:
String sql = "select t from ticket t where createdBy = :user and t.subject like :summary";
query = genericDAOImpl.getHibernateSession().createQuery(sql);
query.setParameter("user", userId);
query.setParameter("summary", "%" + inputBean.getSummary + "%");

Related

Hibernate null parameter native query Spring Boot

I am trying to pass a null parameter (:searchQuery) to a native query in Spring Boot, I have tried various different ways but whenever I pass null I get the error
ERROR: operator does not exist: text ~~ bytea
Query
#Query(value = "SELECT count(*) FROM analysis_history ah, analysis_group ag WHERE ah.analysis_group_id = ag.id "
+ "AND ah.creation_date BETWEEN :from AND :to AND ((:searchQuery IS NULL) OR (:searchQuery IS NOT NULL AND ag.name LIKE :searchQuery))", nativeQuery = true)
Long count(#Param("from") Date from, #Param("to") Date to, #Param("searchQuery") String searchQuery);
Can anyone help?
You cannot use like null
SELECT count(*) FROM analysis_history ah, analysis_group ag
WHERE ah.analysis_group_id = ag.id AND ah.creation_date
BETWEEN :from AND :to AND ag.name LIKE :searchQuery
And you pass '%' in the searchQuery when the searchQuery parameter is null? e.g.
repository.count(from, to, searchQuery == null ? "%" : searchQuery);
There is a way to bypass this, but you need access to the EntityManager, and not use the #Query annotation to create that implementation for you.
Long count(Date from,Date to, String searchQuery) {
Number n = em.createNativeQuery("... that query")
.setParameter("from", from, TemporalType.DATE) // assuming that's a Date, and not TimeStamp
.setParameter("to", to, TemporalType.DATE)
.setParameter("searchQuery", "")
.setParameter("searchQuery", searchQuery)
.getSingleResult();
return n.longValue();
}
The first call to .setParameter("searchQuery", "") tells Hibernate what type this is, the next one sets the value.
The problem comes from Postgres doing the typecheck during parsing, and not deferring the error in case the parameter set is a null.
An alternative workaround to the issue posed by #coladict, which is compatible with Query and performs as well as the original would.
SELECT count(*)
FROM analysis_history ah, analysis_group ag
WHERE ah.analysis_group_id = ag.id
AND ah.creation_date BETWEEN :from AND :to
AND (:searchQuery IS NULL OR ag.name LIKE CAST(:searchQuery AS CHARACTER VARYING))

How to get the data in query(search result of hql)?

I am a novice to use jdbc and I have some problems.
I use hql to search data in MySQL, and the result is Query type. I don't know how to get the data from the "Query".This is my code:
final String hql = "select app.appkey,app.type from " + getClassName() +
"app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
Thanks a lot.
You have to do the following:
final String hql = "select app.appkey,app.type from " + getClassName() + " app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
query.list(); //or query.getSingleResult();
query.list() will give a list of results.
query.getSingleResult() will give you a object.
You can check this.
If you are expecting a list of results, so:
List<Object[]> results = query.getResultList();
If you are expect one single result:
Object[] result = query.getSingleResult(); // if more than one result was found, this method will throw a NonUniqueResultException
If column information will be stored in a position of the Object array. Example:
String appKey = (String) result[0];
String appType = (String) result[1];
But work with Object array is not good. Try to use Dto, like explained here.

linq Command not getting the answer for DB

i have a table(UserQuestions) in my DB(WebSiteUsers) which contains QuestionID field as a Primary key and QuestionContext field which holds the Questions that are asked as its value.
Now i want to have a textBox that show me the QuestionContext Value by getting QuestionID.
I used these linq commands and none of them bring me the correct answer :
string Questioncontext = new WebSiteUsersEntities().UserQuestions.Where(p => p.QuestiuonID.ToString() == QuestionID).Select(p => new { p.QuestionContext}).ToString();
string Questionx = (from q in new WebSiteUsersEntities().UserQuestions where q.QuestiuonID.ToString() == QuestionID select q.QuestionContext).ToString();
QuestionCntxt.Text = Questionx;
the outcome is like this :
SELECT
[Extent1].[QuestionContext] AS [QuestionContext]
FROM [dbo].[UserQuestion] AS [Extent1]
WHERE CAST( [Extent1].[QuestiuonID] AS nvarchar(max)) = #p__linq__0
I guess your QuestionID variable is of type string, while the database column is of type int.
So rather than using
q.QuestiuonID.ToString() == QuestionID
criteria inside the query, convert the variable to int and use that as criteria.
Also ToString just gives you the SQL query text, not the result. Use ToList if you expect more than one result or FirstOrDefault if you expect zero or one results:
var questionID = int.Parse(QuestionID);
string Questioncontext = new WebSiteUsersEntities().UserQuestions
.Where(p => p.QuestiuonID == questionID)
.Select(p => p.QuestionContext)
.FirstOrDefault();
Note that I also changed the select to return directly QuestionContext string rather than anonymous object having QuestionContext property.

linq like empty string

var list = (from i in _dataContext.aspnet_Users.Include("aspnet_Membership") where i.UserName.Contains(userName) select i ).ToList();
if userName="" then nothing return. how can i do that if empty string then return all records?
Do:
var list =
(from i in _dataContext.aspnet_Users.Include("aspnet_Membership")
where string.IsNullOrEmpty(userName)
|| i.UserName.Contains(userName)
select i ).ToList();
Fun Fact: The System.Data.Linq.SqlClient namespace includes a few helper methods that are pretty useful.
You can use the SqlMethods.Like function which will return all results if an empty string is passed to it.
Ex:
(from i in _dataContext.aspnet_Users.Include("aspnet_Membership")
where SqlMethods.Like(i.UserName, "%" + userName + "%")
select i).ToList();

Linq Error: InvalidOperationException: Could not translate expression

Get value out of DateTime column
if null to return String.Empty
else
DateTime.ToShortDateString
What am I doing wrong => query produced below:
var queryable = from p in Products
select new {
selldate = p.SellEndDate == null
? string.Empty
: p.SellEndDate.Value.ToShortDateString() };
Error: InvalidOperationException: Could not translate expression 'Table(Product).Select(p => new <>f__AnonymousType01(selldate = IIF((p.SellEndDate = null), Invoke(value(System.Func1[System.String])), p.SellEndDate.Value.ToShortDateString())))' into SQL and could not treat it as a local expression.
Basically what's happening here is that LINQ to SQL is taking your entire query and trying to convert it into something that SQL Server can understand. The problem, though, is that SQL Server has no concept of DateTime.ToShortDateString, so the conversion to SQL fails.
You'll have to change your query so that it just selects SellEndDate (which will get it as a Nullable<DateTime>) and then when you use the results of that query you can do the conversion to string. For example:
var list = (from p in Products
select p.SellEndDate).ToList();
// calling ToList() above means we have the entire resultset in memory and
// no longer have to pass the query back to SQL Server
var stuff = from p in list select new
{
selldate = p.SellEndDate == null ?
string.Empty :
p.SellEndDate.Value.ToShortDateString()
};
ToShortDateString doesn't seem to have equivalent SQL translation.
Use ToString instead.
If the date time field allows nulls:
from order in repository.Order
select order.OrdShipDate == null ? "" : order.OrdShipDate.GetValueOrDefault(DateTime.Now).Month.ToString() + "/" + order.OrdShipDate.GetValueOrDefault(DateTime.Now).Day.ToString() + "/" + order.OrdShipDate.GetValueOrDefault(DateTime.Now).Year.ToString();
If the date time field doesn't allow nulls:
from order in repository.Order
select order.OrdShipDate.Month.ToString() + "/" + order.OrdShipDate.Day.ToString() + "/" + order.OrdShipDate.Year.ToString();

Resources