Recently, If you are using Hibernate 5.2 or higher, then the Query::list() method has been deprecated.
Now, what the difference in using these two methods?
If anyone knows, please explain with examples.
The documentation of Hibernate 3.2 says that Query#list() returns the query as List<T>.
Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].
As you can read from the newer documentation of Hibernate 5.2 about the same named class and its method Query#getResultList is the overridden implementation of the the javax interface's method TypedQuery#getResultList.
Execute a SELECT query and return the query results as a typed List.
This method is a replacement of the one from the previous versions.
The idea is to implement Java EE interface (most of javax library) and keep the naming consistent.
Related
How can i use jpa for query over an object (not an entity)?
For example this simple code:
String [] theList = {a,b,c,d}.
Query q = new Query("Select tl from theList tl")
Reason behind: the queries are dynamically created and executed, but the objects in the from clause of the jpql query aren't necessarily mapped tables. In some cases there are just an Object, So the actual behavior needed is modify the query during execution of the program to meet the criteria, but i don't know how to modify the query.
Edit: I Don't use native queries because of portability of code. It will be the last option.
What you're looking for is called LINQ, and unfortunately (?) it is available only in C#.
However, you can partially emulate it with Stream(s).
A Stream offers basically all the operators you need
.filter() where
.max() max
.sorted() orderby
.limit() limit
.skip() offset
.collect(groupingBy()) group by
And so on. Just give a look at the Javadoc!
I think 'JdbcTemplate' would suffice your requirement.
JdbcTemplate gives you the flexibility to run native queries and map them to a Java class.
However, you'll have to explicitly map your Java class with the column names in the database.
I have solved using joSQL. Is a powerfull opensource tool that allows you to query over java objects using "sql". It is not jpa but satisfied my needs.
Another tool i have seen that do that is called querydsl.
In this answer, the author mentions that to avoid NPE the fetchValue(query) method can be used. The problem is that how exactly can the OP's code be converted into a query? I have similar code, pasted below, and would like to turn it into a query also.
return jooqDSLContext.select()
.from(CL_LOGIN)
.join(CL_USERS)
.on(CL_LOGIN.CL_USER_ID.eq(CL_USERS.CL_USER_ID))
.where(CL_USERS.EMAIL1.eq(email))
.fetchOne().into(CL_LOGIN);
JOOQ is very powerful and has many capabilities, but unfortunately everything I have tried to make a standalone query object with a join does not even compile.
EDIT: The answer provided did help me side-step the need to have a query object. But for those that want to know how to get a query object you can use the getQuery() method... see example below.
SelectQuery<Record1<String>> query = jooqDSLContext.select(USER_LOGIN.ACCOUNT_STATUS)
.from(USER_LOGIN)
.where(USER_LOGIN.USER_ID.eq(userId))
.getQuery();
Observe the signature of the method DSLContext.fetchValue(ResultQuery<R>), where R extends Record1<T>. This means that the expected row type of the query is Record1<T> with any arbitrary <T> type. In other words, you must project exactly one column in your SELECT clause.
You seem to want to project the entire record of type CL_LOGIN, so fetchValue() is not applicable to your use-case.
But note, there's also ResultQuery.fetchOneInto(Table), which is a convenience method wrapping that null check and the into() call. So, just write:
return jooqDSLContext.select()
.from(CL_LOGIN)
.join(CL_USERS)
.on(CL_LOGIN.CL_USER_ID.eq(CL_USERS.CL_USER_ID))
.where(CL_USERS.EMAIL1.eq(email))
.fetchOneInto(CL_LOGIN);
I recently had a similar issue as this SOer had, where I was using Hibernate's Query#list object and getting compiler warnings for type safety.
Someone pointed out to me that I could use EntityManager#createQuery(String,Class<?>) instead of Query#list to accomplish the same thing but have everything genericized correctly.
I've been searching for examples of using Hibernate directly with EntityManager but so far no luck. So I ask: how can I use the EntityManager#createQuery method in lieu of the Query#list method when doing a SELECT from Hibernate?
Using JPA 2 with EclipseLink implementation.
I'm trying to build a dynamic query which should bring me some records persisted after a given date.
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Event> criteria = builder.createQuery(Event.class);
Root<Event> root = criteria.from(Event.class);
criteria.select(root);
criteria.distinct(true);
List<Predicate> predicates = new ArrayList<Predicate>();
//...
if (dateLimit != null){
ParameterExpression<Date> param = builder.parameter(Date.class, "dateLimit");
predicates.add(builder.lessThanOrEqualTo(root.get("dateCreated"), param));
}
lessThanOrEqualTo() and le() are the only two methods in the API which look like may help me in this case. This warning is thrown by the eclipse though:
Bound mismatch: The generic method lessThanOrEqualTo(Expression<? extends Y>, Expression<? extends Y>)
of type CriteriaBuilder is not applicable for the arguments (Path<Object>, ParameterExpression<Date>).
The inferred type Object is not a valid substitute for the bounded parameter
<Y extends Comparable<? super Y>>
I can imagine that I'm not taking the correct approach for this problem but I can't find anywhere some tips or pointers for a possible solution.
The problem is that with the string-based API it cannot infer the type for the result value of the get-Operation. This is explained for example in Javadoc for Path.
If you use
predicates.add(builder.lessThanOrEqualTo(root.<Date>get("dateCreated"), param));
instead, it will work fine, because it can figure out the return type from the type argument and will find out that it is comparable. Note, the use of a parameterised method invocation root.<Date>get(...) (see, e.g., When is a parameterized method call useful?).
Another (in my opinion better) solution is to use the metamodel based API instead of the string-based one. A simple example about canonical metamodel is given for example here. If you have more time to invest, this is a good article about static metamodel: Dynamic, typesafe queries in JPA 2.0
You need to use the generated metamodel to access the attributes is a really safe way. If you use Strings to refer to your attributes, types can only be deduced from the explicit generic type used when calling the method, or by a type cast, or by the automatic type inference done by the compiler:
Path<Date> dateCreatedPath = root.get("dateCreated");
predicates.add(builder.lessThanOrEqualTo(dateCreatedPath, dateLimit));
I was getting a similar error but with the syntax predicates.add(cb.greaterThan(article.get(Article_.created), since)); and found this page. The cause for me, turned out to be that I had upgraded my project from Java 1.7 to 1.8, and in the process had configured Maven to compile for Java 1.8 as well. I simply had to change Maven compiles back to 1.7, while keeping the rest of the project at 1.8, to fix the error.
I had the same problem, when I have worked with predicates. It worked great with all types except Date type. I tried all method and most simple way for me was:
predicates.add(builder.greaterThanOrEqualTo(root.get(criteria.getKey()), (Date)criteria.getValue()));
I added (Date) before criteria.getValue(), what help to recognize my value Object as Date type.
My Java (JDK6) project uses Spring and JDBCTemplate for all its database access. We recently upgraded from Spring 2.5 to Spring 3 (RC1). The project does not use an ORM like Hibernate nor EJB.
If I need to read a bunch of records, and do some internal processing with them, it seems like there are several (overloaded) methods: query, queryForList and queryForRowSet
What should be the criteria to use one instead of the other? Are there any performance differences? Best practices?
Can you recommend some external references for further research on this topic?
I find that the standard way to access as list is via the query() methods rather than any of the other approaches. The main difference between query and the other methods is that you'll have to implement one of the callback interfaces (either RowMapper, RowCallbackHandler, or ResultSetExtractor) to handle your result set.
A RowMapper is likely what you'll find yourself using most of the time. It's used when each row of the result set corresponds to one object in your list. You only have to implement a single method mapRow where you populate the type of object that goes in your row and return it. Spring also has a BeanPropertyRowMapper which can populate the objects in a list via matching the bean property names to the column names (NB this class is for convenience not performance).
A RowCallbackHandler is more useful when you need your results to be more than just a simple list. You'll have to manage the return object yourself you are using this approach. I usually find myself using this when I need a map structure as my return type (i.e. for grouped data for a tree table or if I'm creating a custom cache based of the primary key).
A ResultSetExtractor is used when you want to control the iteration of the results. You implment a single method extractData that will be the return value of the call to query. I only find myself using this if I have to build some custom data structure that is more complex to build using either of the other callback interfaces.
The queryForList() methods are valuable in that you don't have to implement these callback methods. There are two ways use queryForList. The first is if you're only querying a single column from the database (for example a list of strings) you can use the versions of the method that takes a Class as an argument to automatically give you a list of only objects of those classes.
When calling the other implementations of queryForList() you'll get a list back with each entry being a map of for each column. While this is nice in that you are saved the expense of writing the callback methods, dealing with this data structure is quite unwieldy. You'll find yourself doing a lot of casting since the map's values are of type Object.
I've actually never seen the queryForRowSet methods used in the wild. This will load the entire result of the query into a CachedRowSet object wapped by a Spring SqlRowSet. I see a big downside in using this object in that if you're passing the SqlRowSet around to the other layers of your application, you're coupling those layers to your data access implementation.
You shouldn't see any huge performance differences between any of these calls except as I mentioned with the BeanPropertyRowMapper. If you're working with some complex manipulation of a large result set, you might be able to get some performance gains from writing an optimized ResultSetExtractor for your specific case.
If you want to learn more I would consult the Spring JDBC documentation and the JavaDoc for the classes I've mentioned. You can also take a look at some of the books on the Spring Framework. Though it's a bit dated Java Development with the Spring Framework has a very good section on working with the JDBC framework. Most of all, I would say just try writing some code with each method and see what works best for you.
Since you are in the wonderful Generics land, what you may really want to do is to use SimpleJdbcTemplate and use its query() methods for Lists of objects and queryForObject() for individual objects. Reasoning for this simply is that they're even easier to use than the ones in JdbcTemplate.
One small addition to the excellent answers above: additional methods, like queryForInt, queryForLong, queryForMap, queryForObject, etc. might seem like good options at times if you're running a simple query and expect a single row.
However, if you could get 0 or 1 rows back, the queryForList method is generally easier, otherwise you'd have to catch IncorrectResultSizeDataAccessException. I learned that the hard way.