I'm trying to sort a resultset using the SQL statement Order by using JPA, on a datetime column data type with this string, on a Mysql database:
Query query = em.createQuery("SELECT e FROM Events e Order by e.EventDateTime;");
Using the createQuery method java returns the error:
SEVERE: Local Exception Stack:
Exception [EclipseLink-8030] (Eclipse Persistence Services - 2.3.0.v20110604-r9504):
org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [Events.findByGameId: SELECT e FROM Events e WHERE e.gameId =
:gameId ORDER BY e.EventDateTime DESC], line 1, column 59: unknown state or association field [EventDateTime] of class [com.jogogestao.entity.Events].
at org.eclipse.persistence.exceptions.JPQLException.unknownAttribute(JPQLException.java:457)
at org.eclipse.persistence.internal.jpa.parsing.DotNode.validate(DotNode.java:88)
at org.eclipse.persistence.internal.jpa.parsing.OrderByItemNode.validate(OrderByItemNode.java:52)
at org.eclipse.persistence.internal.jpa.parsing.OrderByNode.validate(OrderByNode.java:61)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:210)
I tried sorting by the integer type primary and all runs ok...but this is not what I want of course.
Using createNativeQuery the statement runs ok...
Query query = em.createNativeQuery("SELECT * FROM Events Order by EventDateTime;");
The only problem is that the return object is not an Events type object (from the entity) and I can't convert to this type.
Maybe the problem is that JPA does not support sorting on datetime fields?
How can I get around this?
I'm using Netbeans 7.0.1, Glassfish 3.1.1, MySql 5.5.19 Community Server (GPL) and mysql-connector-java-5.1.15-bin.jar.
Thanks!
SELECT e FROM Event e ORDER BY e.eventDateTime
you don't have * - you have to specify the entity you select
don't put a semicolon at the end
use all-lower-case keywords, capital-case entity names, and lower-camel-case property names
name the entity in singular, not plural (Event vs Events)
The message is clear: you don't have an EventDateTime mapped property (or field, if fields are mapped directly) in the entity Events. If you respect the Java conventions, the field/property should be named eventDateTime, and not EventDateTime.
Related
I'm using Spring Boot 1.5.2 and the following #Query:
#Query(value = "SELECT m FROM Message m WHERE m.from.userId = :myId OR m.to.userId = :myId GROUP BY m.from.userId, m.to.userId ORDER BY m.date DESC")
List<Message> chatOverview(#Param("myId") final Long myUserId);
The intention of the query is to create a chat messenger overview, where you see the last message of each conversation you had. It works fine for me in dev, but in production (newer MySQL database version) I get this error:
java.sql.SQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'message0_.message_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
I read in this thread what the reason for this change was, however I couldn't find a way to fix this with JPA / Spring. I cannot change any settings in the production MySQL database and I would like to avoid any upgrading in Spring either. How can I fix my query?
Here is the definition and purpose of the GROUP BY (see section 4.7) clause:
The GROUP BY construct enables the aggregation of result values according to a set of properties.
That means it is used only if you're aggregating (sum, avg, max, min, ...) the value(s) of a field(s). But in your case I don't see any aggregation function. So just remove the GROUP BY clause and everything should be fine:
SELECT m FROM Message m WHERE m.from.userId = :myId OR m.to.userId = :myId ORDER BY m.date DESC
Grouping on userId doesn't make sense too because all the entities returned by this query will have the same value for this field.
We are dealing with sybase database in core java code. We are using org.eobjects.metamodel.DataContext to parse query.
String sCol[]=table.getColumnNames();
Query query=dataContext.query().from(table.getName()).select(sCol).toQuery();
return new QueryIterator(dataContext.executeQuery(query).iterator());
But it executing query. Same code working fine with Oracle database to parse and execute query.
Some of query example generated are :
select City.CityName from ownername.City
select City.CityName from City
select CityName from ownername.City
select CityName from City
select ownername.City.CityName from ownername.City
SELECT "City"."CityName" FROM ownername."City"
select * from ownername.City
No any of above query executed. We are getting these errors :
Not capable of parsing FROM token: "ownername"."City"
Could not execute query: The column prefix '"City"' does not match with a table name or alias name used in the query. Either the table is not specified in the FROM clause or it has a correlation name which must be used instead.
Not capable of parsing SELECT token: ownername.City.CityName
How can we execute query using metamodel wih SYBASE database OR is there any other way to execute sybase queries?
Oracle (and Microsoft) use a schema logical construct that Sybase ASE does not. In SAP/Sybase ASE, all tables and columns in a database are in the same schema. It is possible to users to have their own objects in the database though, so there is the possibility of imitating some of the schema behavior using user ownership, but it would require an extra level of effort.
For Sybase the proper query syntax would be:
SELECT [ Col1, Col2 | * ]
FROM [dbName].[ownerName.]TABLE
In your case
SELECT CityName
FROM dbName.ownername.City
In Sybase ASE, it's typically best practice to have all objects owned by 'dbo', so in that case you can omit the owner from the query:
SELECT CityName
FROM dbName..City
Full query syntax and information can be found in the Query Section of the Transact SQL Users Guide in the documentation.
The error messages you're getting are coming from MetaModel's query parser layer. It is searching for matching column and table names in the metadata of your database before it's even firing the query.
I notice that you're using namespace "org.eobjects.metamodel". You should upgrade to Apache MetaModel ("org.apache.metamodel") if possible since a lot has been improved in MetaModel since it's introduction into Apache. Including a lot of query parser improvements.
I've an entity class with lob field called RAW (eclipselink JPA provider and sql server), also I'm using querydsl to query to database. But I've this problem...
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: The text data type cannot be selected as DISTINCT because it is not comparable.
Error Code: 421
Call: SELECT DISTINCT ID, ALTA, ANIO, FECHARECEPCION, INSTITUCION, MES, RAW, VERSION FROM ARCHIVO WHERE (FECHARECEPCION BETWEEN ? AND ?)
bind => [2013-01-01 00:00:00.0, 2014-01-31 23:59:59.0]
Query: ReadAllQuery(referenceClass=Archivo sql="SELECT DISTINCT ID, ALTA, ANIO, FECHARECEPCION, INSTITUCION, MES, RAW, VERSION FROM ARCHIVO WHERE (FECHARECEPCION BETWEEN ? AND ?)")
Any suggestions?
The query is
QArchivo archivo = QArchivo.archivo;
JPAQuery query = from(archivo);
query.where(archivo.institucion.eq(institucion));
query.where(archivo.fechaRecepcion.between(fechaInicio, fechaTermino));
List<Archivo> resultado = query.list(archivo);
return resultado;
It is odd that it is using a DISTINCT when you called list() not listDistinct(), and seemed to not have called distinct(). Double check that you are not calling distinct() anywhere. DISTINCT in normally only used with joins, so since you are not using any, it is very odd that it is used.
You could also try the same query through JPQL or the Criteria API, it should not use DISTINCT unless to specify it.
If you want to use DISTINCT and have a LOB, then you cannot select the LOB. You can either put the LOB in its own table and reference it through a OneToOne, or make its fetch=LAZY.
You can also reword the query to use a sub-select so that the distinct in only in the sub-select.
i.e.
Select a from Archivo a where exists (select a2 from Archivo a2 where ... and a = a2))
I am developing web application using JSP and Servlet (IDE: Eclipse, Container: Tomcat7.0, DB: Oracle 10)
I want to get data from two table in a single query
Query:
query = "select * from PROTOCOL as a, ACTIONS as b where a.PROTOCOL_ID = b.PROTOCOL_ID";
But after running the application I am getting the following exception:
java.sql.SQLException: ORA-00933: SQL command not properly ended
is there anything wrong in query?
The problem you have is keyword AS. This is used for columns in SELECT section. It is not valid for FROM where you specify the tables.
You have
select * from PROTOCOL as a, ACTIONS as b
should be
select * from PROTOCOL a, ACTIONS b...
From Oracle Docs
t_alias
Specify a correlation name, which is alias for the table, view,
materialized view, or subquery for evaluating the query. This alias is
required if the select list references any object type attributes or
object type methods. Correlation names are most often used in a
correlated query. Other references to the table, view, or materialized
view throughout the query must refer to this alias.
Example:
SELECT select_list
FROM table1 t_alias1
WHERE expr operator
(SELECT column_list
FROM table2 t_alias2
WHERE t_alias1.column
operator t_alias2.column);
wrong alias syntax. try the following:
query = "select * from PROTOCOL a,ACTIONS b where a.PROTOCOL_ID = b.PROTOCOL_ID";
A comment here for anyone may need it.. PostgreSQL seems to accept AS next to FROM/JOIN
Is it possible to get HQL results with dot.
for example:
select Employee.name as 'Employee.name'
I know that mysql allows that, is there any support fir that in hibernate.
This is the exeption that I get:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: . near line 1, column 42 [SELECT Affiliate.affiliateId as Affiliate.affiliateId , parent.userName as parent_userName , Affiliate.userName as Affiliate_userName , Affiliate.email as Affiliate_email , parent.affiliateId as parent_affiliateId , employee.firstName as employee_firstName , Affiliate.name as Affiliate_name FROM com.affiliates.hibernate.Affiliate Affiliate INNER JOIN Affiliate.employee as employee INNER JOIN Affiliate.parent as parent WHERE 1=1 AND Affiliate.employee='1']
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
Because of architecture problems, "_" instad of "." cant work for me.
Thanks
I'm not sure if I understood your question correctly. You are thinking about writing queries. Hibernate supports its internal language called HQL. To be honest I prefer using JPA and hibernate as JPA implementation. In such case you have to write your queries with Criteria Api or using JPA query language. Query language is very convenient in conjunction with NamedQueries. So if you are using HQL or JPA, the easiest way is to select object with some name
SELECT e FROM Employee e WHERE p.name = ?1
The other possibility is using NativeQuery, here is an example.