query runs fine in sql developer, but crashes in hibernate - sql

When I run this in sqldeveloper:
SELECT CASE
WHEN TABLE1.COL1 IS NOT NULL
THEN (
CASE
WHEN TABLE1.COL2 IS NOT NULL
THEN TABLE1.COL3
ELSE TABLE1.COL4
END)
WHEN TABLE1.COL5 IS NOT NULL
THEN TABLE1.COL6
ELSE TABLE1.COL7 END "C" FROM TABLE1
it runs fine.
When I run this through a Hibernate session, it gives:
No Dialect mapping for JDBC type: -101
All cols are of type varchar2. col1 is of type number.
The database is oracle 10g.
A workaround is also welcome, if a solution is not obvious :)
Also, how can I find out what is the JDBC type -101 referring to. I have seen -1 but not -101 before.
EDIT: I tried using a return scalar on top of the named query No luck.
EDIT#2: Is there a way to see what is the datatype returned for "C". Then I use one of the solutions provided in the answer.

This error comes when we pass a parameter through query rather than putting the value directly. In case of SQL you can regenerate the same by giving value as C= :S and entering the value in the new textbox generated. Solution to this problem comes in an upgrade patch as this is a bug.

I've never faced it on Oracle, but sometimes JDBC returns strange types for complex expressions in queries, and Hibernate can't resolve these types.
In such cases you can try to add explicit cast to the query:
SELECT CAST((CASE ... END) AS varchar2) "C" FROM TABLE1

if axtavt's answer doesn't work you can define your own type mapping following this pattern:
public class MySQL5Dialect extends org.hibernate.dialect.MySQL5Dialect
{
public MySQL5Dialect()
{
super(); // register additional hibernate types for default use in scalar sqlquery type auto detection
registerHibernateType(Types.LONGVARCHAR, Hibernate.TEXT.getName());
}
}
Of course you have to use the value you are getting instead ov longvarchar and the apropriate Hiberante types.
(I nicked the code sample here: http://opensource.atlassian.com/projects/hibernate/browse/HHH-1483

Related

jOOQ - support for UPDATE ... SET ... query with arbitrary degree

I have two functions: one returns a list of fields, the other returns a select query (which selects the corresponding values of the fields).
private List<Field<?>> fields() {
....
}
private Select<?> select() {
...
}
Note that the degree is determined at runtime, it depends on the user input. Hence List<Field<?>> and Select<?>.
It is possible to insert into a table:
context.insertInto(table, fields()).select(select()))
It is not possible to update a table:
context.update(table).set(DSL.row(fields()), select())
Could this functionality be added to jOOQ 3.7?
Which workaround can we use for now?
Nice catch, there's a missing method on the UpdateSetFirstStep DSL API, which accepts RowN as a first argument, the type returned from DSL.row(Collection). This should be fixed for jOOQ 3.7:
https://github.com/jOOQ/jOOQ/issues/4475
As a workaround, and if you can live with the guilt of the hack, you could cast to raw types:
context.update(table).set((Row1) DSL.row(fields()), (Select) select())
You can cast DSL.row(fields()) to Row1, because the internal implementation type returned by DSL.row(fields()) implements all Row[N] types.

QueryDSL + PathBuilder + cast to string

I am filtering PrimeFaces DataTables using dynamic filters.I have this working using Spring org.springframework.data.jpa.domain.Specification.Now I am wondring how to do the same using QueryDSL.
Using specification I can use javax.persistence.criteria.Root to get a javax.persistence.criteria.Join, use javax.persistence.criteria.Expression.as(Class<String> type) to cast it to String and finally use javax.persistence.criteria.CriteriaBuilder.like(Expression<String> x, String pattern, char escapeChar).
How do I do the same in QueryDSL ? I can get PathBuilder using new PathBuilder<T>(clazz, "entity") (do you really have to use the variable here? I would like my class to be generic...) but then the com.mysema.query.types.path.PathBuilder.get(String property) returns new PathBuilder instead of an Expression.
If I try to use com.mysema.query.types.path.PathBuilder.getString(String property) I get java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Integer].
Seems like the part I am missing is the cast.
I'm quite sure someone was dealing with the same thing already.
Thanks.
Edit: Stack trace for IllegalArgumentException
Trying to search for text "1" inside integer column using com.mysema.query.types.path.PathBuilder.getString(String property) - that's where I need the cast to happen :
Caused by: java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Integer]
at org.hibernate.ejb.AbstractQueryImpl.validateParameterBinding(AbstractQueryImpl.java:375)
at org.hibernate.ejb.AbstractQueryImpl.registerParameterBinding(AbstractQueryImpl.java:348)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:375)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:442)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72)
at com.mysema.query.jpa.impl.JPAUtil.setConstants(JPAUtil.java:44)
at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:130)
at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:97)
at com.mysema.query.jpa.impl.AbstractJPAQuery.list(AbstractJPAQuery.java:240)
at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.findAll(QueryDslJpaRepository.java:102)
...
To get a valid condition you will need to take the types of the properties into account, e.g.
pathBuilder.getNumber(Integer.class, property).stringValue().like(likePattern)
I was researching a similar topic until I came across this aged question. I hope my answer will be helpful to some.
I think the possible solution lies (exclusively) outside of QueryDSL. You can use common Java reflection to obtain the field type, something like
Class type = clazz.getDeclaredField(criteria.getKey()).getType();
// don't forget to catch exception if field doesn't exist ..
switch(type.getSimpleName()) {
case "String":
StringExpression exp = entityPath.getString(...);
}
That way you can have a reasonably dynamic implementation.

VB.Net Linq to Entities Null Comparison - 'Is Nothing' or '= Nothing'?

We have several projects in VB.Net, using .Net Framework 4 and Linq to Entities for many of our SQL queries. Moving to EF is a new shift for us (been using it for about 4-6 months) and has the backing of upper management because we can code so much faster. We still use a lot of stored procs, but we even execute those through Linq to Entities as well.
I'm hoping to clear some confusion up and I can't find a direct answer that makes sense. We have some queries where we want records where a specific field has a NULL value. These are simple select queries, no aggregates or left joins, etc. Microsoft recommends the query look something like this MSDN Link:
dim query = from a in MyContext.MyTables
Where a.MyField = Nothing
Select a
I have several projects where I do exactly this and it works great, no warnings in the IDE. Recently a new project was created by another developer and when he did his null check like above, we all get this warning in the IDE:
Warning 1 This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.
Comparing the projects, option explicit and option strict are on for each one. If we ignore the warning, we get the exact record set we are looking for when the app runs. The warning goes away if I change the = sign to IS. But why did this warning appear in one project and not others? It's confusing when even on MSDN there are examples using the equals operator.
Generated column should be a Nullable(Of T)
So you can check if that field has value or not like this:
dim query = from a in MyContext.MyTables
Where Not a.MyField.HasValue
Select a
I believe what you're seeing here is that MyField is a Nullable(Of T) type. Likely a primitive Integer, Single, etc ...
The reason you're seeing this warning is because the compiler promotes the normal equality operator for the primitive type to the Nullable(Of T) version. It essentially executes the following
Dim myField As Integer? = a.MyField
Dim other As Integer? = Nothing
If myField = other Then
...
End If
The issue though is that when Integer? has the value Nothing it won't compare equal to anything. Hence the above Where clause will always return False. The compiler is attempting to warn you about this problematic corner of Nullable(Of T) and push you to a Is Nothing check which will determine if a.MyField has a non-null value.
This blog article has a very detailed explanation of why this warning is being generated and all of the mechanics behind it. The article is written for C# but the basic premise is applicable to VB.Net as well.
http://blogs.msdn.com/b/abhinaba/archive/2005/12/14/503533.aspx
At least in LINQ to objects you can use this instead:
Nullable(Of Integer).Equals(a, b)
This works fine with both, either or none of the two values being Nothing.

NHibernate ISQLQuery SetParameter issue

This is probably fairly straightforward but i can't seem to find a reasonable explanation in any documentation.
I'm trying to use an NHibernate.ISQLQuery and using SetResultTransformer() to return a custom set of results from a custom SQL query. Like so:
public virtual IList<T> GetSQLObject<T>(string sql, IDbParameter[] parameters = null)
{
ISQLQuery qry = _sess.CreateSQLQuery(sql);
qry.SetResultTransformer(Transformers.AliasToBean(typeof(T)));
if (parameters != null) {
foreach (IDbParameter parameter in parameters) {
qry.SetParameter(parameter.Name, parameter.Value);
}
}
return qry.List<T>();
}
From looking at the examples, it seems that in the sql query I have to use parameters in the format :param1 instead of #param1 as I would in a standard SQL query. If i use the latter syntax in the query, it throws an error at qry.SetParameter().
Is there a reason why ISQLQuery/NHibernate requires them in this format and won't work with the normal syntax?
SQL Server uses #param, but not every other database does. For example, MySQL uses ?param
NHibernate allows you to swap out 1 database implementation for another with little to no reworking of your DAL. It sets the parameters based on the database you configured when you setup the NH Configuration.
Edit: Also I think :param came about from Hibernate being targeted at Oracle when it was initially developed, since Oracle uses :param
Phil has answered the "why"; so perhaps I can recommend a "how"; why not just add a new extension method to the IDbParameter type (something like .GetNHibernateName() ) that will return the parameter name with the "#" replaced with a ":"; that should be trivial to implement.

How to retrieve multiple rows from a stored procedure with Linq to SQL?

I've recently started to work with Linq to SQL and wondered how to get multiple rows as a result of executing a stored procedure,here's a simple sp i want to work with:
CREATE PROCEDURE gsp_ftsmultiple
#SearchKey varchar(100)
AS
BEGIN
SET NOCOUNT ON;
SELECT Label, theContent
FROM FtsTest
WHERE FREETEXT( theContent, #SearchKey )
END
Executing this sp from management studio is fine,but the corresponding method in the generated context class returns a int value, and I don't know how to get the actual rows, tried using the OUT parameters, but they can return only one result.
I think all you need to do is make a class that matches your result schema and make sure the function in the dbml has it as a return type.
see here on msdn
Try creating the fulltext predicates as wrapper functions instead of sprocs, like this. Worked for me.
When sqlmetal generates the code for this procedure, it doesn't pass a valid argument for the query to work.
Try to put something like this on the top of you SP:
IF #SearchKey IS NULL OR LEN(#SearchKey) = 0
BEGIN
SELECT N'' AS Label, N'' AS theContent WHERE 1 = 0
END
[...]
It will now deduce that 2 NVARCHAR columns are the usual output and generate code accordingly
PS. Code off my head, untested
Mike
I tested the following code snippet and it worked fine. If you put the generated code here, I can take a look and check where is the problem. Anyway, you can create a partial class as same name as your generated data context class and add the desired method manually as follows.
public partial class FooDataContext: System.Data.Linq.DataContext
{
[System.Data.Linq.Mapping.Function(Name = "GetFoo")]
public System.Data.Linq.ISingleResult<Foo> GetFoo()
{
System.Data.Linq.IExecuteResult res = base.ExecuteMethodCall(this, (System.Reflection.MethodInfo)System.Reflection.MethodInfo.GetCurrentMethod());
return (System.Data.Linq.ISingleResult<Foo>)res.ReturnValue;
}
}
You'd might be better off just running the query in itself, seeing as you're not really doing anything that requires a procedure. Just make sure you escape the search key properly.