JPA in Netbeans, strange thing - java

I encountered the following problem.
I have simple (just started) web application.
I created new Web Application project and generated entity with #ManyToOne (so there are to enitities in fact) class from the database. This is what happens when i try to run it.
First run:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group WHERE (group_id = 1)' at line 1 Error Code: 1064 Call: SELECT group_id, acc_level, name FROM group WHERE (group_id = ?) bind => [1 parameter bound] Query: ReadObjectQuery(name="file:/D:/Projekty/Sell Your Thing/build/web/WEB-INF/classes/_Sell_Your_ThingPU" referenceClass=Group1 )
Second run: Everything is correct
After making Netbeans to recompile (for example I add a space somewhere) i get this:
com.model.User cannot be cast to com.model.User
After few refreshes of the page i get this:
WEB9031: WebappClassLoader unable to load resource [sun.reflect.ConstructorAccessorImpl], because it has not yet been started, or was already stopped
I am so confused right now:/
(I use glassfish and mysql)
edit:
I resolved the firt error by changing the name from group to user_group because its a keyword.
I also resolved the last error by adding
<property name="openjpa.DynamicEnhancementAgent" value="false"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
in persistance.xml
I still cannot resolve the casting one. I don't understand why i have some class leak or whatever it is while I have really simple code. (generated entities in netbeans)
method causing errors:
public String getUserNameById(int id) {
em = getEntityManager();
Query q = em.createNamedQuery("User.findByUserId");
q.setParameter("userId", id);
User u = (User) q.getSingleResult();
em.close();
return u.getName();
}
and i just use it in JSF
<h:outputText value="#{userBean.getUserNameById(2)}" />

The first error is likely caused by the fact that you chose group as the name of your table. group being a reserved SQL keyword, the query is invalid. Choose another name (and don't choose select, order or insert as the name :-))

Related

Hibernate and Postgres positional parameteres mismatch

I am currently maintaining a legacy application which uses some old technologies: Hibernate 3.2, Spring 2.5 and the like.
I've been fighting the last days with an exception. I've managed to isolate a simple example:
private void test(String username) {
String sql = "from org.ojade.aas.authentication.model.User u " +
"where u.aasPrincipalName = ?";
Session session = sessionFactory.getCurrentSession();
QueryImpl query = (QueryImpl) session.createQuery(sql);
query.setParameter(0, username);
List list = query.list();
log.debug("list = {}", list);
}
The execution of this code throws an exception when query.list() is executed.
Caused by: org.postgresql.util.PSQLException: No value specified for parameter 2.
at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:102)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:166)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:389)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:330)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:240)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:92)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:187)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1791)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2217)
... 120 more
There is no parameter 2. If I change the query to use named parameters it works, but I can't change the original code (is part of a compiled library).
I've set Hibernate to show me the SQL. It is executing this:
SELECT
user0_.ID_PRINCIPAL AS ID1_3_,
user0_.VERSION AS VERSION3_,
user0_.NO_PRINCIPAL AS NO4_3_,
user0_.IN_BLOQUEO AS IN5_3_,
user0_.IN_ACTIVO AS IN6_3_
FROM JAAS_PRINCIPAL user0_
WHERE user0_.TT_DISCRIMINANTE = 'USER' AND user0_.NO_PRINCIPAL =?
Which seems ok.
Any idea what the problem may be?
This old bug reported against the postgresql-8.1-405.jdbc3.jar driver informs that if you have /* */ comments including a ? in the query, the parser won't understand that it's not a placeholder, but just part of the comment. Apparently other characters such as dollar signs also caused problems.
As given in the original bug report, this can be solved with named parameters, fixing comments (in this case the comments were generated by Hibernate, so turning off Hibernate comments with property hibernate.use_sql_comments=false fixes it) or by upgrading the driver to handle it more gracefully (no idea which version it was fixed though).
Quite a catch to come across this in 2017! :)

Hibernate: column does not exist

When I try to load an Entity with Hibernate I get the following error in postgres-log:
ERROR: column appuser0_.device_token does not exist at character 35
STATEMENT: select appuser0_.id as id1_27_0_, appuser0_.device_token as device_t2_27_0_,....
The column device_token definitely exists - and if I copy-paste the whole logged statement and execute it in PGAdmin, I get the expected result.
So what do I forget? What is the difference between the Hibernate statement and the manually executed one?
This issue was caused by the multi tenant configuration so that the wrong DataSource has been chosen.
Depending on how you defined the query, the problem might be located somewhere else: For example, HQL Queries are using the "property-names" of the class, not the column names.
And if you have something like:
#Column("device_token")
private String deviceToken;
Then your HQL-Query should target "deviceToken" and not "device_token". We also encountered a similar error once: Hibernate was reporting "user_id" is missing, because we named the property "userId" with the underscored version for the column name only.
This might be not the problem for you but worth double checking it.

QuerySyntaxException: Path expected for join

I have a query:
SELECT year_body.year, count(year_body.year) as toOrder
FROM YearBody year_body
LEFT JOIN session Session WITH year_body.sessionID = Session.sessionID
LEFT JOIN version appVersion WITH session.applicationVersion = appVersion.version
WHERE year_body.eventTime > :period and session.ipAddress NOT LIKE :ip and version.is_release = 1
GROUP BY (year_body.year)
ORDER BY toOrder DESC
This query works in MySQL workbench, but when I actually use it in Java I get the error:
QuerySyntaxException: Path expected for join!
I have already got through other errors by switching ONs to WHENs as well as fixing mapping issues but I am not sure how to fix this problem.
I decided to use a native query and my code works well after removing the object mapping references SESSION and appVersion

Wso2 Data service giving java.lang.NullPointerException

I created a web service using wso2 data service. But when I try to test it it gives below error.
Below is the screenshot of the error.
You are getting this error, because you haven't defined the result of your select query. When you define a SELECT query, you are going to retrieve a resultset from the query. So you need to define the result using the output parameters.
In the Add Query page there is a section called 'Result (Output Mapping)' where you can define the resut.
Alternatively you can define the query with column names (ex: SELECT name, age from Student) and then just click on 'Generate Responses' which automatically generate the response[1].
[1]http://docs.wso2.org/display/DSS301/Generate+Response

"No row with the given identifier exists" although it DOES exist

I am using Hibernate and getting
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [#271]
What is pretty weird about this error is, that the object with the given id exists in the database. I inserted the problematic record in another run of the application. If I access it in the same run (i.e. same hibernate session) there seem to be no problems retrieving the data.
Just because it could be a fault of the mapping:
public class ProblemClass implements Persistent {
#ManyToOne(optional = false)
private MyDbObject myDbObject;
}
public class MyDbObject implements Persistent {
#OneToMany(mappedBy = "myDbObject")
private List<ProblemClass> problemClasses;
#ManyToOne(optional = false)
private ThirdClass thirdClass;
}
I have absolutely no clue even where to look at. Any hints highly appreciated!
Just to clarify:
The data was inserted in another RUN of the application. It is definitely in the database, as I can see it via an SQL-Query after the application terminated. And after THAT, i.e. when starting the application again, I get the error in the FIRST query of the database -- no deletion, no rollback involved.
Addition:
Because it was asked, here is the code to fetch the data:
public List<ProblemClass> getProblemClasses() {
Query query = session.createQuery("from ProblemClass");
return query.list();
}
And just to make it complete, here is the generic code to insert it (before fetching in another RUN of the application):
public void save(Persistent persistent) {
session.saveOrUpdate(persistent);
}
Eureka, I found it!
The problem was the following:
The data in the table ThirdClass was not persisted correctly. Since this data was referenced from MyDbObject via
optional = false
Hibernate made an inner join, thus returning an empty result for the join. Because the data was there if executed in one session (in the cache I guess), that made no problems.
MySQL does not enforce foreign key integrity, thus not complaining upon insertion of corrupt data.
Solution: optional = true or correct insertion of the data.
Possible reasons:
The row was inserted by the first session, but transaction was not committed when second session tried to access it.
First session is roll-backed due to some reason.
Sounds like your transaction inserting is rollbacked
Main reason behind this issue is data mismatch, for example i have entity mapping class called "X" and it has column "column1" and it has reference to the table "Y" column "column1" as below
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "column1", referencedColumnName = "column1")
public Y getColumn1() {
return Y;
}
In this if X table column1 has value but Y table column1 is not having the value. Here link will be failed.
This is the reason we will get Hibernate objectNotFound exception
This issue can also be resolved by creating proper data model like creating proper indexing and constraints (primary key/foreign key) ..
This might be your case, kindly check my answer on another post.
https://stackoverflow.com/a/40513787/6234057
I had the same Hibernate exception.
After debugging for sometime, i realized that the issue is caused by the Orphan child records.
As many are complaining, when they search the record it exists.
What i realized is that the issue is not because of the existence of the record but hibernate not finding it in the table, rather it is due to the Orphan child records.
The records which have reference to the non-existing parents!
What i did is, find the Foreign Key references corresponding to the Table linked to the Bean.
To find foreign key references in SQL developer
1.Save the below XML code into a file (fk_reference.xml)
<items>
<item type="editor" node="TableNode" vertical="true">
<title><![CDATA[FK References]]></title>
<query>
<sql>
<![CDATA[select a.owner,
a.table_name,
a.constraint_name,
a.status
from all_constraints a
where a.constraint_type = 'R'
and exists(
select 1
from all_constraints
where constraint_name=a.r_constraint_name
and constraint_type in ('P', 'U')
and table_name = :OBJECT_NAME
and owner = :OBJECT_OWNER)
order by table_name, constraint_name]]>
</sql>
</query>
</item>
2.Add the USER DEFINED extension to SQL Developer
Tools > Preferences
Database > User Defined Extensions
Click "Add Row" button
In Type choose "EDITOR", Location - where you saved the xml file above
Click "Ok" then restart SQL Developer
3.Navigate to any table and you will be able to see an additional tab next to SQL, labelled FK References, displaying FK information.
4.Reference
http://www.oracle.com/technetwork/issue-archive/2007/07-jul/o47sql-086233.html
How can I find which tables reference a given table in Oracle SQL Developer?
To find the Orphan records in all referred tables
select * from CHILD_TABLE
where FOREIGNKEY not in (select PRIMARYKEY from PARENT_TABLE);
Delete these Orphan records, Commit the changes and restart the server if required.
This solved my exception. You may try the same.
Please update your hibernate configuration file as given below:
property start tag name="hbm2ddl.auto" create/update property close tag
I have found that in Oracle this problem can also be caused by a permissions issue. The ProblemClass instance referred to by the MyDbObject instance may exist but have permissions that do not allow the current user to see it, even though the user can see the current MyDbObject.

Categories