Getting exception in retrieving data using hibernate - java

I'm retrieving data from my database using hibernate but getting an error.
My code for retrieving data is:

I got the answer. Actually, I have to pass the name of class i.e. mapped to required table.
Query query= session.createQuery("from Register");
instead of
Query query = session.createQuery("from bank_employee") ;

Related

JDBC - select query from a materialized view does not work

I'm trying to create a select query from a materialized view using jdbc. Here is my actuall code:
Query q = entityManager.createNativeQuery("SELECT v.name FROM my_materialized_view v");
List<Object[]> authors = q.getResultList();
But when I run this code I get the following error:
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
There's an specific to select materialized views in this context? Because if I use that code querying from a normal table it works perfect...
dont use SQL ALIAS
try
"SELECT name FROM my_materialized_view"

hibernate query involving foreign key

I am trying to write a hibernate query which selects a number of records from a table based on some criteria.
I have two relevant tables in my database
tbleventattendees which has the following fields - eventAttendeeRecord tblevent, tblmembers, and memberComments;
tblevent which has the following fields relevant field eventID which is the tblevent foreign key in tbleventattendees
What I am trying to do is write a HQL query which shows the attendees the attendees at specific event e.g. something like this SQL query select * from tbleventattendees where tblevent = 1
However, whilst this works as an SQL query in MySQL workbench when I try from tbleventattendees where tblevent = 1 in Netbeans run HQL Query I get the following error
org.hibernate.QueryException: Incorrect query syntax [ FROM
Society.Tbleventattendees as attendees where Tblevent =1
]
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:259)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:209)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)
Caused by: java.lang.NullPointerException
at org.hibernate.sql.QuerySelect.appendTokens(QuerySelect.java:185)
at org.hibernate.sql.QuerySelect.setWhereTokens(QuerySelect.java:103)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.renderSQL(QueryTranslatorImpl.java:625)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:243)
... 9 more
I think this is because I am using the value in the database in the query rather than the object reference as when I remove the =1 criteria I get the following value in that column
Society.Tblevent#6a2437ae
Can someone please help, I have read through lots of posts on here but struggling to work out the answer
You can write somthing like this:
Query query = session.createQuery("from Tbleventattendees attendees where attendees.tblevent.eventID = :tbleventId ");
query.setParameter("tbleventId", "1");
List list = query.list();

Get specific columns of table in hibernate using addEntity

I am familiar with Java but really new with ORM and Hibernate.
I am using the following query to get the resultset of all columns of a table in hibernate.
(List<Neighborhood>)session.createSQLQuery("SELECT * FROM Neighborhood").addEntity(Neighborhood.class).list();
I want to get only two specific column from this table. I looked up over the internet but not able to find the solution which can be used as a modification of above statement.
I tried the below query but getting - SQLGrammarException: could not extract ResultSet
(List<Neighborhood>)session.createSQLQuery("SELECT neighborhoodName,educationYouth FROM Neighborhood").addEntity(Neighborhood.class).list();
Edit:
Two more attempted queries after #scaryWombat's suggestion. Both give the same exception
First
List list = session.createSQLQuery("SELECT neighborhoodName,educationYouth FROM Neighborhood").list();
Second
String sql = "SELECT neighborhoodName,educationYouth FROM Neighborhood";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();
Edit2:
After #Tehmina's solution, I am getting one error - java.sql.SQLException: Column 'educationYouth' not found because educationYouth is an object of class name "EducationYouth".
In the Neighborhood table there is no column with name educationYouth but all the column from EducationYouth class.
Try this
(List<Neighborhood>)session.createSQLQuery("SELECT * FROM Neighborhood").list();
To avoid the overhead of using ResultSetMetadata, or simply to be more explicit in what is returned, one can use addScalar():
(List<Neighborhood>)session.createSQLQuery("SELECT * FROM Neighborhood").addScalar("neighborhoodName", Hibernate.STRING).addScalar("educationYouth", Hibernate.STRING);
Or try this
Hibernate automatically converts the data into appropriate type. The automatic conversion does not work in all cases and in that case we have an overloaded version of addScalar():
SQLQuery q = session.createSQLQuery("SELECT * FROM Neighborhood");
q.addScalar("neighborhoodName");
q.addScalar("educationYouth");
List<Object[]> rows = q.list();
for (Object[] row : rows) {
System.out.println(row[0] + " " + row[1] );
Don't forget to check in the hibernate config file
<!--hibernate.cfg.xml -->
<property name="show_sql">true</property>
I hope it would resolve your error.

Syntax Error when retrieving data from database by joining two tables in Hibernate Sql

String query ="From transaction JOIN outlet transaction.outlet_ref_id = outlet.outletid WHERE(transaction.added_date_time between'"+sdate+"' and '"+edate+"') and (outlet.merchant ="+merchantId+")";
This is the query I'm using to retrieve data from the data base. This is working when I'm using this query in Navicat and gives data. But I'm using this as a hibernate query it gives following error.
you need to write query Link : from Company as comp inner join comp.employees as emp.
Company as comp means entityName as referenceName.
From Transaction t JOIN Outlet o t.outlet_ref_id = o.outletid WHERE(t.added_date_time between'"+sdate+"' and '"+edate+"') and (o.merchant ="+merchantId+")
use Entity name on Transaction
for more refer :
http://www.concretepage.com/hibernate/hibernate-hql-associations-and-inner-join-left-outer-join-right-outer-join-cross-join-example
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
http://levelup.lishman.com/hibernate/hql/joins.php

how to execute the stored procedure in hibernate 3

I am new in hibernate. I am using hibernate 3 in my application using hibernate annotations , I am developing application in struts 1.3.
My question is :
I have googled a lot but could not understand how to call a stored procedure in hibernate using annotations , I have a simple scenario : suppose I have 2 fields in my jsp say 1) code 2) name , I have created a stored procedure in database for inserting those records into table. Now my problem is that how to execute it
List<MyBean> list = sessionFactory.getCurrentSession()
.getNamedQuery("mySp")
.setParameter("code", code)
.setParameter("name", name)
I don't know the exact code how to do this. But I guess something like that actually I come from jdbc background therefore have no idea how to do this and same thing I want when selecting the data from database using stored procedure.
Hibernate provides many simple ways to call a SP like
Native SQL
Named Query in native SQL as Annotation/XML mapping file
Following link shows how each of above can be implemented
http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#sp_query
Sample to run native SQL query using hibernate:
Session session = getSession();
SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(id) FROM tableName WHERE external_id = :external_id");
sqlQuery.setParameter("external_id", idValue);
int count = ((BigInteger) sqlQuery.uniqueResult()).intValue();
releaseSession(session);
You can execute your stored procedure using Hibernate's SQLQuery with the same SQL as when you call it against the database. For example, in postgreSQL:
String query = "select schema.procedure_name(:param1)";
SQLQuery sqlquery = sessionFactory.getCurrentSession().createSQLQuery(query);
sqlquery.setInteger("param1", "this is first parameter");
sqlQuery.list();
Hope it helps.

Categories

Resources