PSQLException: ERROR: syntax error at or near "TableName" Position: 1 - sql

Hi I am trying to execute a native SQL query but getting the exception as below
The query i am trying to execute is as below:
public List<Category> getAllCategories(){
List<Category> categories = getEntityManager().createNativeQuery("Category.getAllAfterMerge", Category.class).getResultList();
return categories;
}
and the NamedNative Query is as below
#NamedNativeQuery(name="Category.getAllAfterMerge", query="SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME, C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON FROM CATEGORY C LEFT JOIN REFERENCE_VALUES R ON C.ID = R.REFERENCE_VALUE_CODE AND R.REFERENCE_OBJ_NAME = 'CATEGORY';")
The Tables are as below
CREATE TABLE category
(
id bigserial NOT NULL PRIMARY KEY,
code text NOT NULL,
name text NOT NULL,
parent_id bigint,
path text,
comp_id bigint,
created_on timestamp without time zone,
modified_on timestamp without time zone,
)
And the Reference_Values table is as below
CREATE TABLE reference_values
(
id serial NOT NULL PRIMARY KEY,
reference_obj_name text,
reference_value_code bigint,
display_name text,
created_on timestamp without time zone,
modified_on timestamp without time zone,
)
The entities are as below Category.java
#Entity
#Table(name = "category")
#NamedNativeQuery(name="Category.getAllAfterMerge", query="SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME, C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON FROM CATEGORY C LEFT JOIN REFERENCE_VALUES R ON C.ID = R.REFERENCE_VALUE_CODE AND R.REFERENCE_OBJ_NAME = 'CATEGORY';")
public class Category extends Persistent {
private static final long serialVersionUID = 1L;
#ManyToOne
private Category parent;
#OneToMany(mappedBy = "parent")
private Set<Category> children;
private String code;
private String name;
private String path;
#Column(name = "comp_id")
private Integer compId;
And the ReferenceValues.java as below
#Entity
#Table(name = "reference_values")
#NamedQuery(name = "ReferenceValues.findAll", query = "SELECT r FROM ReferenceValues r")
public class ReferenceValues extends Persistent implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "display_name")
private String displayName;
#Column(name = "reference_obj_name")
private String referenceObjName;
#Column(name = "reference_value_code")
private Long referenceValueCode;
exception is as below:
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:492)
at getAllCategories(JpaCategoryDAO.java:18)
at CategoryServiceImplTest.testGetAllCategories(CategoryServiceImplTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:670)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2115)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2610)
at org.hibernate.loader.Loader.doList(Loader.java:2593)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422)
at org.hibernate.loader.Loader.list(Loader.java:2417)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1980)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
... 31 more
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "Category"
Position: 1
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2284)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2003)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:200)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:424)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:161)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:114)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 46 more

You need to use createNamedQuery() method for the named queries and add resultClass to the #NamedNativeQuery
List<Category> categories = getEntityManager()
.createNamedQuery("Category.getAllAfterMerge").getResultList();
#NamedNativeQuery(name = "Category.getAllAfterMerge",
query = "SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME,
C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON
FROM CATEGORY C LEFT JOIN REFERENCE_VALUES R ON C.ID =
R.REFERENCE_VALUE_CODE AND R.REFERENCE_OBJ_NAME = 'CATEGORY'",
resultClass = Category.class)
Probably, you need to use quotes for the aliases
COALESCE(R.DISPLAY_NAME, C.NAME) as \"NAME\"

Related

Hibernate SQL query matching more than one members of an ElementCollection

I have Pojo mapped with JPA annotations like this
#Entity
#Table(name = "record")
public class SearchRecord {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String vidName;
#ElementCollection
private List<String> videoLabels = new ArrayList<String>();
and would like to run a Hibernate query that filters out all SearchRecords that match/contain 1..n videoLabels. (only objects that match all of the videoLabels)
I was able to search for SearchRecords that match a single label by running the following query:
String labelCar = "Car";
String labelPerson = "Person";
TypedQuery<SearchRecord> query = em.createQuery("SELECT b FROM SearchRecord b JOIN b.videoLabels l WHERE l = :param1",SearchRecord.class);
query.setParameter("param1", labelCar);
List<SearchRecord> results = query.getResultList();
But how can I execute a query filtering out all SearchResults matching Car and Person?
Thanks for your support
I was able to solve the problem with the following query
SELECT DISTINCT a FROM SearchRecord a JOIN a.labels b JOIN a.labels c WHERE b.name = 'Car' and c.name = 'Person'

Error when doing inner join with cross cache join

I have a studentinfo cache for StudentInfo class and a classinfo cache for ClassInfo,
These two classes are used to do join(Student has an attribute of classId)
With the following code snippet,
SqlFieldsQuery innerJoinSQL = new SqlFieldsQuery(
"select StudentInfo.studentId, StudentInfo.name, StudentInfo.classId from StudentInfo as a, " +
"\"class_cache\".ClassInfo as b where a.classId = b.classId");
cursor = studentCache.query(innerJoinSQL);
for (List data : cursor) {
System.out.println(String.format("studentId %s, studentName %s, classId %s, className %s", data.get(0), data.get(1), data.get(2), data.get(3)));
}
I got following exception:
Exception in thread "main" javax.cache.CacheException: Failed to parse query: select a.studentId, a.name, a.classId, b.name from StudentInfo a, 'class_cache'.ClassInfo b on a.classId = b.classId
at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryTwoStep(IgniteH2Indexing.java:1137)
at org.apache.ignite.internal.processors.query.GridQueryProcessor$2.applyx(GridQueryProcessor.java:732)
at org.apache.ignite.internal.processors.query.GridQueryProcessor$2.applyx(GridQueryProcessor.java:730)
at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:1666)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.queryTwoStep(GridQueryProcessor.java:730)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:700)
at ignite.sqlgrid.join.IgniteSQLJoinQueryTest.main(IgniteSQLJoinQueryTest.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT A.STUDENTID, A.NAME, A.CLASSID, B.NAME FROM STUDENTINFO A, 'class_cache'[*].CLASSINFO B ON A.CLASSID = B.CLASSID "; expected "identifier"; SQL statement:
select a.studentId, a.name, a.classId, b.name from StudentInfo a, 'class_cache'.ClassInfo b on a.classId = b.classId [42001-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.getSyntaxError(DbException.java:205)
at org.h2.command.Parser.readIdentifierWithSchema(Parser.java:3115)
at org.h2.command.Parser.readTableFilter(Parser.java:1202)
at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1884)
at org.h2.command.Parser.parseSelectSimple(Parser.java:2032)
at org.h2.command.Parser.parseSelectSub(Parser.java:1878)
at org.h2.command.Parser.parseSelectUnion(Parser.java:1699)
at org.h2.command.Parser.parseSelect(Parser.java:1687)
at org.h2.command.Parser.parsePrepared(Parser.java:443)
at org.h2.command.Parser.parse(Parser.java:315)
at org.h2.command.Parser.parse(Parser.java:287)
at org.h2.command.Parser.prepareCommand(Parser.java:252)
at org.h2.engine.Session.prepareLocal(Session.java:560)
at org.h2.engine.Session.prepareCommand(Session.java:501)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:73)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:276)
at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.prepareStatement(IgniteH2Indexing.java:406)
at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryTwoStep(IgniteH2Indexing.java:1121)
... 12 more
Can some help where the problem is? Thanks!
Looks I figured out the problem.
My two pojo(StudentInfo and ClassInfo) for each cache has one same column named classId. Looks only one pojo can set index = true with annotation #QuerySqlField(index = true) on the classId field
But I am not sure that Ingite has such constraint. If someone knows, let confirm, thanks!

join 2 columns and get only matched vlaues in hibernate

I have 2 tables:
course: id, name
student: id, course_id, age
Tables are tied with oneToMany annotation
I am trying to write a hibernate query against course that will return courses and students that are x years 0ld. That's my attempt:
SELECT c from Course c RIGHT JOIN c.student p ON p.age = 20
It returns a course that has at least one student that is 20. when there are more students that are not 20, they are included in the result set as well. Is there a way to restrict the joined table values?
Edit:
These are my entities:
public class Course implements Serializable {
private static final long serialVersionUID = 646349111982187812L;
#Id
#Column(name = "id", unique=true, nullable=false)
private String id;
#Column(name = "name", unique=false, nullable=false)
private String name;
#OneToMany(cascade={CascadeType.ALL, CascadeType.REMOVE},
fetch=FetchType.LAZY, mappedBy = "Course")
#OrderBy("age")
#JsonManagedReference
private Set<Student> students;
getters and setters ...
}
public class Student implements Serializable {
private static final long serialVersionUID = 646349221337813L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "age", unique=false, nullable=true)
private String age;
#ManyToOne()
#JsonBackReference
private Course course;
}
I am trying to use this method from my crudrepository to get the expected result:
#Query(?????)
public List<Course> findCoursesWithAdults(#Param("age")int age)
it sounds like you want an inner join instead of a right join
SQL
SELECT distinct c.* from Course c inner join Student p on (c.id=p.course_id and p.age=20)
or with hql
select distinct c from Course c inner join c.student p with p.age=20
in order to get the information you are requesting, you will either have to limit the Set in Course using #Where ("age = 20" ) or simply deal with a list of students instead of courses.
select p from Course c inner join c.student p with p.age=20
you can reference the attached course object through any one of the getCourse methods on the student objects. You could also use "group by" here to help you order things.
or you can use a filter within the hibernate Entity...
#Transient
public List<Students> getStudents(Integer age){
List<Students> tmp = new ArrayList<>();
for(Student s: getStudents())
if(s.getAge().equals(age))tmp.add(s);
return tmp;
}
one more edit and im done... there is another way to do this that i didnt mention..
a select wrapper query.
create a wrapper object for your course and student
public class CourseWrapper(){
private Course c;
private List<Students> p = new ArrayList<>();
....constructor ... getters ...setters
}
select new CourseWrapper(c, students)
from Course c
left outer join c.students p with p.age=20'
more info here
SELECT c.name, s.id
FROM course c
INNER JOIN student s ON c.id = s.course_id
WHERE s.age = 20

add Nhibernate Projections

Have Employee: BaseEntity class with
public virtual BaseEntity Department {get;set;}
public virtual BaseEntity Position {get;set;}
and BaseEntity class:
public virtual long Id {get;set;}
public virtual long Name {get;set;}
How can I map my entities and /create select like this
SELECT DepartmentTable.nvarchar1 as Department, PositionTable.nvarchar1 as Position, COUNT(*) as N
FROM AllUserData EmployeeTable
left outer join AllUserData PositionTable on EmployeeTable.int2=PositionTable.tp_ID
left outer join AllUserData DepartmentTable on EmployeeTable.int3=DepartmentTable.tp_ID
WHERE EmployeeTable.tp_ListId = #p0 and PositionTable.tp_ListId = #p2 and DepartmentTable.tp_ListId = #p1
GROUP BY DepartmentTable.nvarchar1, PositionTable.nvarchar1;
I tried like this:
var criteria = session.CreateCriteria<Entities.Employee>();
criteria.CreateAlias("Position", "PositionTable", JoinType.LeftOuterJoin);
criteria.Add(Restrictions.Or(Restrictions.Eq("PositionTable.ListId", Program.PositionListGuid), Restrictions.IsNull("PositionTable.Id")));
criteria.CreateAlias("Department", "DepartmentTable", JoinType.LeftOuterJoin);
criteria.Add(Restrictions.Or(Restrictions.Eq("DepartmentTable.ListId", Program.DepartmentListGuid), Restrictions.IsNull("DepartmentTable.Id")));
criteria.Add(Restrictions.Eq("ListId", Program.EmployeeListGuid));
var projectionList = Projections.ProjectionList();
projectionList.Add(Projections.RowCount());
projectionList.Add(Projections.GroupProperty("Department"), "AliasedId");
criteria.SetProjection(projectionList);
criteria.SetResultTransformer(Transformers.AliasToBean(typeof(BaseEntity)));
var list = criteria.List<BaseEntity>();
// "More than one row with the given identifier was found" exception raised here
I'am confused, should I somehow use joined table alias for Projections.GroupProperty, rework my mapping/Entity to use only primitive types (string, int) or any other approach?
Figured out:
Add int Number to BaseEntity and string DepartmentName, string PositionName to Employee. Now I can use Projections to map Sql grouped by result to this properties:
var pl = Projections.ProjectionList()
.Add(Projections.RowCount(), GetEntityProperty(typeof (BaseEntity), "Number"))
.Add(Projections.GroupProperty("DepartmentTable.Title"), "PositionName")
.Add(Projections.GroupProperty("PositionTable.Title"), "DepartmentName");
ICriteria criteria = session.CreateCriteria<Employee>()
.CreateAlias("Position", "PositionTable", JoinType.LeftOuterJoin)
.Add(Restrictions.Eq("PositionTable.ListId", Program.PositionListGuid))
.CreateAlias("Department", "DepartmentTable", JoinType.LeftOuterJoin)
.Add(Restrictions.Eq("DepartmentTable.ListId",Program.DepartmentListGuid))
.Add(Restrictions.Eq("ListId", Program.EmployeeListGuid))
.SetProjection(pl)
.SetResultTransformer(Transformers.AliasToBean<BaseEntity>());
var list = criteria.List<BaseListEntity>().ToList();

Query for Many-To-Many relation using hibernate

I have a many To many relation in my resource classes using hibernate. In the Category class:
#Entity
public class Category {
Id
#GeneratedValue
private long id;
#ManyToMany
#JoinTable(name = "category_activity",
joinColumns = { #JoinColumn(name = "Category_id") },
inverseJoinColumns = { #JoinColumn(name = "activities_id") })
private Collection<Activity> activities;
}
And in the Activity class:
#Entity
public class Activity {
#Id
#GeneratedValue
private long id;
#ManyToMany
#JoinTable(name="category_activity",
joinColumns={#JoinColumn(name="activities_id")},
inverseJoinColumns={#JoinColumn(name="Category_id")})
private Collection<Category> category;
}
When I had oneToMany relation between them I was using a Query that worked fine for me:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Collection<Activity> activities = (Collection<Activity>) session.createQuery("from Activity as a where a.category.id=" + categoryId + " order by a.key").list();
session.getTransaction().commit();
I appreciate any help that I can fix this query for the ManyToMany relation?
I also used this query :
activities = (List<Activity>) session.createQuery("from Activity a join a.category cs where cs.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
and I got this error in stack trace:
<html><head><title>Apache Tomcat/7.0.23 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server encountered an internal error () that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.Comparable
java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
java.util.ComparableTimSort.sort(Unknown Source)
java.util.ComparableTimSort.sort(Unknown Source)
java.util.Arrays.sort(Unknown Source)
java.util.Collections.sort(Unknown Source)
se.softwerk.timelog.controller.ActivityManager.activityList2(ActivityManager.java:64)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
</pre></p><p><b>note</b> <u>The full stack trace of the root cause is available in the Apache Tomcat/7.0.23 logs.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.23</h3></body></html>
First of all you shouldn't be concatenating strings, that opens the door for SQLInjection attacks, you should be using named parameters. More on named parameters here
Second, if you have ManyToMany relationshio, both sides should be pluralized:
This
private Collection<Category> category;
Should be this:
private Collection<Category> categories;
Now on your particular question, you have this
from Activity as a where a.category.id= :categoryId order by a.key
You need this:
from Activity a join a.category cs where cs.id= :categoryId order by a.key