How to use the IN clause while using EntityManager with Hibernate - sql

How do I exactly write the following query using entityManager.
Select * from TABLE_NAME where column_name in ('A', 'B');
I tried with the setParametrList() method. However, it says that this method is not available for type Query.
Query query = entityManager.createQuery(
"Select t from TableEntity t WHERE t.name =:bd AND t.staus in (:statuses)", TableEntity .class)
.setParameter("bd", bd)
.setParameterList("statuses", statuses);
Error: The method setParameterList(String, List<String>) is undefined for the type TypedQuery<TableEntity >
The same method seems to work fine while using session.createQuery. Any suggestions on this.

Just use setParameter("statuses", statuses) with the list. The method checks if the parameter is a collection and expands it.

Related

DbContext.DbSet.FromSql() not accepting parameters

I have a database with two tables, and wrote a relatively simple select statement that combines the data and returns me the fields I want. In my SQL developer software it executes just fine.
Now to execute it in my C# .NET Core application, I created a "fake" DbSet in my DbContext that doesn't have a proper table on the database. The Type of the DbSet is a Model that represents the resulting data structure of the select statement. I use the DbSet field to access the method FromSql() and execute the select like so:
List<ProjectSearchModel> results = _ejContext.ProjectSearch.FromSql(
#"SELECT combined.Caption, combined.Number FROM
(SELECT p.Caption, p.Number, CreateDate FROM dbo.Project AS p
UNION
SELECT j.Caption, j.Number, CreateDate FROM dbo.Job AS j) AS combined
WHERE combined.Caption LIKE '{0}%' OR combined.Number LIKE '{0}%'
ORDER BY combined.CreateDate DESC
OFFSET 0 ROWS
FETCH FIRST 30 ROWS ONLY", term)
.ToList();
The SQL does properly return data, I've tested that. But the result variable holds 0 entries after executing. In the documentation for FromSql() I found that with MS SQL Servers you have to use OFFSET 0 when using ORDER BY so that's what I did.
I have no idea what I'm doing wrong.
You need to use DbQuery<T> instead:
public DbQuery<Project> ProjectSearch { get; set; }
Then, you can issue arbitrary queries using FromSql on that. With DbSet, the query must be composable, which means it can only be a standard select, it must correspond to a real table, and must include all properties on the entity - none of which apply to the query you're trying to perform.
As #ChrisPratt said, one of my mistakes was using the DbSet class instead of the DbQuery class. But also, what drove me crazy is that my parameters didn't work. My mistake was putting them inside a string, which results in them not being recognized as parameters. So my SQL string should be
...
WHERE combined.Caption LIKE {0} + '%' OR combined.Number LIKE {0} + '%'
...
instead of
...
WHERE combined.Caption LIKE '{0}%' OR combined.Number LIKE '{0}%'
...

How can I create a SELECT EXISTS (subquery) with jOOQ?

I want to build and execute a query like this with jOOQ.
SELECT EXISTS( subquery )
For exemple:
SELECT EXISTS(SELECT 1 FROM icona_etiqueta WHERE pvp IS NULL AND unitat_venda = 'GRAMS')
How can I do it? Can it be done?
Found it. I was looking for a selectExists method and got confused by the DSL.exists() predicate constructor.
There is a much more convenient fetchExists(subquery).
My specific example is resolved like this:
create.fetchExists(
create.selectOne()
.from(ICONA_ETIQUETA)
.where(ICONA_ETIQUETA.PVP.isNull(),
ICONA_ETIQUETA.UNITAT_VENDA.eq('GRAMS'))
);
Which directly returns a boolean.
Your own solution is the most convenient approach to what you want to be doing. A more general approach is to use:
create.select(field(exists(...)));
Where you wrap a Condition (created by DSL.exists(Select)) in a Field using DSL.field(Condition). As of jOOQ 3.9, Field<Boolean> and Condition are not the same types. This has changed in the jOOQ 3.17 with #11969. You can now also just write:
create.select(exists(...));

How to select a specific item in django database

How do I translate the following to a Django database search?
SELECT column1 FROM TABLE 'my_table' WHERE column2 = 'some text'
So far I've tried this, which is the wrong syntax:
my_table.objects.get(column1,column2 = 'some text')
Get the model instance by column2 using get() and retrieve the value of column1 field:
my_table.objects.get(column2='some text').column1
Note that if the object would not be found, get() throws DoesNotExist exception which you probably want to handle separately. Also, if there would be more than one object found, it would throw MultipleObjectsReturned exception, which is also something you need to think about beforehand.
Alternatively, you can use filter() with values():
my_table.objects.filter(column2='some text').values('column1')
This would return a ValuesQuerySet (think about it as a list of dictionaries).
There are a couple of ways out , here is one :
obj = my_table.objects.get(column2="any_item").column1

Cast exception in native sql query using hibernate

I have a sql query using tables in it. the result set is return to a bean class which is not mapped to a table in database. the code is here:
SQLQuery q2=ss.createSQLQuery("select tbl_policy.policyNum as POLICYNUM FROM tbl_policy join tbl_product on tbl_policy.FK_productId = tbl_product.pk_product_id join tbl_code on tbl_policy.FK_codeId = tbl_code.PK_codeId join tbl_agriyear on tbl_policy.FK_agriYearId = tbl_agriyear.pk_agriyear_id where tbl_policy.FK_naturalInsurantId = :p1 and tbl_agriyear.AGRIYEAR =:p2");
q2.addScalar("POLICYNUM", Hibernate.STRING);
List<SearchPolicyBean> lsql = (List<SearchPolicyBean>)q2.list();
bean class name is: SearchPolicyBean
when I run it, in this line
System.out.println("Finalllll "+lsql.get(0).getPOLICYNUM());
this error appears:
java.lang.String cannot be cast to BO.SearchPolicyBean
addScalar(String columnAlias)
Is to Declare a scalar query result.
You declared it as a String here q2.addScalar("POLICYNUM", Hibernate.STRING);
So obviously the query results a String list not your SearchPolicyBean pojos .
If you are expectiong an list of your pojo classe you have to use
q2.addEntity(SearchPolicyBean.Class);
And change your query according.
for getting first element:
setPolicyNum((String) ((Object[])polList.get(i))[0]);

Hibernate and boolean mapping from sql query

i have a native sql query to transform (aliasToBean) to a bean with a boolean value.
My query can be something like this:
select val IS NOT NULL as boolValue , ...
or this:
select 1=0 as boolValue, ...
I can not understand how to let Hibernate knows that my bean.boolValue is a Boolan because I get errors in type conversion, in the first case I get a java.math.BigInteger in the second a java.lang.Integer.
Thank you.
You need to tell Hibernate that this column is a boolean, with the SQLQuery.addScalar() method.