What was Hibernate's CriteriaQueryCompiler replaced with? - java

Basically I want to use the code this answer gives https://stackoverflow.com/a/19516794 for my project, but compiler is giving me errors. Documentation mentions that CriteriaQueryCompiler is a temporary implementation.
NOTE : This is a temporary implementation which simply translates the criteria query into a JPAQL query string.
A better, long-term solution is being implemented as part of refactoring the JPAQL/HQL translator.
I'm using Hibernate 4.3.9. Is there an analogous implementation of CriteriaQueryCompiler?

use this import,
import org.hibernate.jpa.criteria.compile.RenderingContext;
and then change CriteriaQueryCompiler.RenderingContext to -> RenderingContext in the function parameters.

Related

StreamResult parameter type in RavenDB query

I took an example from the RavenDB documentation, and adapted it to fit the types I am working with in my code. The type I am using is known (it can be resolved), and the query targets a predefined index. The query uses the spatial option, if that has any part to play in this.
In Eclipse, no matter what type I use for T in this: CloseableIterator<StreamResult<T>> - the error message is always "The type StreamResult is not generic; it cannot be parameterised with arguments <whatever>".
As I'm still quite new to RavenDB, this may well be something obvious that I'm missing.
The type I am working with is a POJO, and consists exclusively of Strings, int and floats.
If you require more info on the index or the type, please let me know.
Thanks !
Pay close attention to your imports ! In my case, it was a simple case of adding the wrong import - because I clicked too fast without verifying that it was the correct library (Eclipse suggested something and I just accepted). It should have been the second option:
net.ravendb.abstractions.data.StreamResult
and NOT
javax.xml.transform.stream.StreamResult
which was first in the list of suggested fixes.

MyBatis Generator setDistinct(true)

I'm trying to use setDistinct(true) as it is described in the guide: http://mybatis.github.io/generator/generatedobjects/exampleClassUsage.html
I've written in this way:
testExample ae = new testExample();
testExample.Criteria criteriatest = ae.createCriteria();
ae.setDistinct(true);
criteriatest.andIDENTLAVEqualTo(Long.parseLong(cert.getCODINDIVID()));
ae.or(criteriatest);
List<test> listtest = testMapper.selectByExample(ae);
but the setDistinct(true) doesn't affect the results.
Where should I add the setDistinct line?
It looks like the link you referenced is for an extremely old version of MyBatis. On that page, it lists the following:
Version: 1.3.3-SNAPSHOT
The latest version is:
mybatis-3.3.0-SNAPSHOT
Grepping the 3.x code for setDistinct does not return anything:
https://github.com/mybatis/mybatis-3/search?q=setDistinct
I'm surprised you don't get a compile-time error about the method not being found. Are you using version 1.3.3 (or 1.x)?
I would recommend doing the DISTINCT right in the query. Since MyBatis is generally a sort of a close-to-the-SQL-metal type of mapping framework, I think it's best to add it in the mapper file's query itself. Plus that way, you can choose specifically what to DISTINCT by. The setDistinct method does not seem to provide any way to specify the target.
For MyBatis 3, I think the analogous style of query would be this:
http://mybatis.github.io/mybatis-3/statement-builders.html
This seems to be analogous to a jOOQ-style DSL. It has a SELECT_DISTINCT method. I personally find it easier to code/read the pure SQL with some XML markup as needed for dynamic SQL in a mapper file, but this is certainly a viable option in MyBatis 3.
Edit:
So, I did some more digging, and the reason I couldn't find the code in the MyBatis3 git repo is because setDistinct is in the mybatis-generator code base.
I think part of the issue here may stem from what is part of Mybatis-Generator's description on GitHub:
MBG seeks to make a major impact on the large percentage of database
operations that are simple CRUD (Create, Retrieve, Update, Delete).
So, it provides a way to do simple DISTINCTs, but with limited control.
The code resides in the addClassElements method of the ProviderSelectByExampleWithoutBLOBsMethodGenerator class. Searching for setDistinct won't show up on a Github search since it's an automatically generated setter.
This is the relevant code snippet:
boolean distinctCheck = true;
for (IntrospectedColumn introspectedColumn : getColumns()) {
if (distinctCheck) {
method.addBodyLine("if (example != null && example.isDistinct()) {"); //$NON-NLS-1$
method.addBodyLine(String.format("%sSELECT_DISTINCT(\"%s\");", //$NON-NLS-1$
builderPrefix,
escapeStringForJava(getSelectListPhrase(introspectedColumn))));
method.addBodyLine("} else {"); //$NON-NLS-1$
method.addBodyLine(String.format("%sSELECT(\"%s\");", //$NON-NLS-1$
builderPrefix,
escapeStringForJava(getSelectListPhrase(introspectedColumn))));
method.addBodyLine("}"); //$NON-NLS-1$
} else {
method.addBodyLine(String.format("%sSELECT(\"%s\");", //$NON-NLS-1$
builderPrefix,
escapeStringForJava(getSelectListPhrase(introspectedColumn))));
}
distinctCheck = false;
}
So, essentially, this looks like it's wrapping the SELECT_DISTINCT method I mentioned originally, and it attempts to introspect the columns and apply the DISTINCT to all of the ones it gets back.
Digging a bit deeper, it ultimately calls this code to get the columns:
/**
* Returns all columns in the table (for use by the select by primary key
* and select by example with BLOBs methods)
*
* #return a List of ColumnDefinition objects for all columns in the table
*/
public List<IntrospectedColumn> getAllColumns() {
List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();
answer.addAll(primaryKeyColumns);
answer.addAll(baseColumns);
answer.addAll(blobColumns);
return answer;
}
So, this is definitely essentially an all-or-nothing DISTINCT (whereas Postgres itself allows DISTINCT on just certain columns).
Try moving the setDistinct to the very last line before you actually invoke the ae object. Perhaps subsequent calls are affecting the column set (although from the code, it doesn't seem like it should -- basically once the columns are set, the setDistinct should use them).
The other thing that would be interesting would be to see what SQL it is actually generating with and without setDistinct.
Check this link out for more detail on debug/logging:
http://mybatis.github.io/generator/reference/logging.html
I'd recommend perhaps trying out the XML-based mapper file definitions which interleave SQL with XML tags for dynamic-ness. IMO, it's much easier to follow than the code Mybatis Generator code snippet above. I suppose that's one of the main tradeoffs with a generator -- easier to create initially, but more difficult to read/maintain later.
For super-dynamic queries, I could see some more advantages, but then that sort of goes against their self-description of it being for simple CRUD operations.

Header Predicate in Apache Camel

After first misspelling i wanted typed support for my predicate expression. So turned to
header(Exchange.FILE_NAME)
as in ...
from("file://src/test/resources/routingtodifferentdestinations-source?noop=true")//
.choice()//
.when(header(Exchange.FILE_NAME).contains("widget.txt"))//
(Q) Where/How happens the distinction between "header.in" and "header.out" in that API.
The equivalent case written in simple, where the distinction is made between in.header and out.header is made explicit:
simple("${in.header.CamelFileName} contains 'widget.txt'"
Thanks
You dont need to concern about IN vs OUT really. Just use IN always. Or better yet do not use in at all, as that is implied, eg ${in.headers.foo} is the same as ${headers.foo}.
See this FAQ
http://camel.apache.org/using-getin-or-getout-methods-on-exchange.html

Modify code at runtime to log return values in Java?

Is there any way of inserting code at runtime to log return values, for instance, using instrumentation?
So far, I managed to insert code when a method exits, but I would like to log something like "method foo returned HashMap { 1 -> 2, 2 -> 3 }"
I'm looking for a general approach that can also deal with, for instance, java.io.* classes. (So in general I'll have no access to the code).
I tried using a custom classloader too, but lot of difficulties arise as I cannot modify java.* classes.
Thanks for the help!
Sergio
Check out BTrace. It's Java, and I believe it'll do what you want.
Have you considered AOP? (Aspect-oriented programming) - if by "I cannot modify java.* classes" you mean you don't have access to the uncompiled code, and cannot add configuration, etc., then that won't probably work for you. In any other case, check that link for examples using Spring-aop:
http://static.springsource.org/spring/docs/2.5.x/reference/aop.html
If not, you could consider solutions based on remote-debugging, or profiling. But they all involve "some" access to the original code, if only to enable / disable JMX access.
Well, since you're looking for everything, the only thing I can think off is using a machine agent. Machine agents hook into the low levels of the JVM itself and can be used to monitor these things.
I have not used DTrace, but it sounds like it would be able to do what you need. Adam Leventhal wrote a nice blog post about it. The link to DTrace in the blog is broken, but I'm sure a quick search and you'll come up with it.
Take a look at Spring AOP, which is quite powerful, and flexible. To start you off on the method foo, you can apply an AfterReturning advice to it as:
#Aspect
public class AfterReturningExample {
#AfterReturning(
pointcut="package.of.your.choice.YourClassName.foo()",
returning="retVal")
public void logTheFoo( Object retVal ) {
// ... logger.trace( "method 'foo' returned " + retVal ); // might need to convert "retVal" toString representation if needed
}
}
The pointcut syntax is really flexible so you can target all the sub packages, components, methods, return values given the expression.

closures mean fully type-safe criteria?

combining closures (FCM) and generics, would it be possible to have fully type-safe criteria.
// The following works without a cast as Foo.id is a 'long' field.
List<Long> ids = session.createCriteria(Foo.class)
.setProjection(Foo#id)
.list();
// The following is a compilation error, as Foo.bar is defined as an int, and not a string
session.createCriteria(Foo.class)
.addRestriction(Restrictions.eq(Foo#bar,"blah"))
.list();
I've read the JPA 2.0 spec for type-safe criteria. But its still somewhat lacking.
Besides, I'm just using criteria here as an example of improving the type-safety of code in general. I used the static typing of java heavily to let me code faster. But as a result I get bitten now and then by the parts of my code that ignore typing. For example HQL queries.
The code you're describing does not use closures but field literals (method literals). Like the good old class literal. These could help in a criteria API. The JPA 2 source code generation work-around for a type-safe query interface could be replaced with it. If it will be part of JDK7.
As Thomas points out, this doesn't strictly require closures. It's all up in the air at the moment, given no-one knows quite what proposal is being looked at. It's not clear if FCM is actually the basis of the proposal, particularly given that Stephen Colebourne seemed to be as susprised as anyone about the announcement.
A lot of people are pointing at Neal Gafter's mysteriously-revised-more-or-less-right-as-the-Devoxx-presentation-announcing-closures-was-being-given spec as a hint as to what form closures might take. Mind you, the revised proposal looks (aesthetically) rather like FCM!
That spec does include the kind of references you refer to (under 'Method References' in the above line), and of course FCM has the same. Yes, this would definitely make you suggest possible. My very first thought when reading about this was how it would affect JPA/Hibernate, and/or our own abstraction layers around same, in this regard. Typesafe, refactorable method references in your criteria? Hell yeah.

Categories

Resources