ClassCastException with java List Iterator with Generics - java

I'm trying to display the names of the hotels using Hibernate. But when I'm iterating the list of hotels which I have got from the database, iter.next() gives a ClassCastException saying Object cannot be cast to Hotel class. This is my method.
public List<Hotel> getAllHotels()
{
List<Hotel> contracts = new ArrayList<Hotel>( );
Transaction tx = null;
Session session = SessionFactoryUtil.getCurrentSession();
try
{
tx = session.beginTransaction();
contracts = session.createSQLQuery("select * from HOTEL").list();
System.out.println("*** Content of the Hotel Table ***");
System.out.println("*** Start ***");
for ( Iterator<Hotel> iter = contracts.iterator(); iter.hasNext();) {
Hotel h = iter.next();
System.out.println(h.getHotelName());
}
System.out.println("*** End ***");
tx.commit();
}
catch( RuntimeException e )
{
if( tx != null && tx.isActive() )
{
try
{// Second try catch as the rollback could fail as well
tx.rollback();
}
catch( HibernateException e1 )
{
System.out.println( "Error rolling back transaction" );
}
// throw again the first exception
throw e;
}
}
return contracts;
}
I have used Generics for the List and Iterator but cannot figure out the error. Any help is appreciated.

Looks like you may need to add the entity when creating the SQLQuery.
Refer https://www.mkyong.com/hibernate/hibernate-native-sql-queries-examples/
session.createSQLQuery("select * from HOTEL").addEntity(Hotel.class).list();
Or if using your current code, iterate through the object array
List result = query.list();
for(Object object : data)
{
//Logic
}

Related

Java List can not retrieve over 90.000 elements

I am dealing with an issue when I attempt to retrieve a large amount of records from a database. It seems that when the amount of records exceed 90.000, the elements can not be retrieved.
When that happens I get the following exception:
com.sun.jdi.ObjectCollectedException occurred while retrieving value.
The code that I am using is the following one:
Session objSession;
List<GroupEntity> colResults;
objSession = this.objSessionFactory.openSession();
try
{
objQuery = objSession.createQuery("FROM GroupEntity WHERE (strDomain = :Domain)")
.setParameter("Domain", strDomain)
.list();
}
catch (Exception objException)
{
throw new GroupException("Could not retrieve the list of WebFiltering groups to scan");
}
objSession.close();
return colResults;
I attempt to page the results retrieved by sets of 1.000, using this method when I insert up to 89.999 records the list is fine. however when I exceed 90.000 I get the same exception.
Any idea about how to face this issue?
In case you process such a big amount of data I'd recommend that you use batch processing with ScrollableResults: https://grokonez.com/hibernate/resolve-hibernate-outofmemoryerror-problem-hibernate-batch-processing
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
ScrollableResults dataCursor = session.createQuery("FROM Data").scroll();
int count = 1;
while (dataCursor.next()) {
Data data = (Data) dataCursor.get(0);
String newText = Utilities.generatedRandomString();
data.setText(newText);
session.update(data);
if (count % 50 == 0) {
System.out.println("============================log: count = " + count);
session.flush();
session.clear();
}
count++;
}
tx.commit();
} catch (Exception e) {
if (null != tx) {
tx.rollback();
}
} finally {
session.close();
}
In this case session will not keep all 90000 records in memory.
"com.sun.jdi.ObjectCollectedException" happens when the object you referring to is garbage collected.
there is no such limit of size on java arrayList.

How to print actual data from list of objects?

I need to Print actual value from below list of objects. Is this possible to get actual values from this list ?
try {
Session session = factory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("select uName1,pass1 from UserRegModel");
List<Object> userList = new ArrayList<Object>();
userList = query.getResultList();
System.out.println("selecting usernaem and pass done");
for (Object temp : userList) {
System.out.println(temp);
}
session.getTransaction().commit();
return userList;
} catch (Exception e) {
System.out.println(e);
}
I get below output. not the actual password and username
Ljava.lang.Object;#2c36b22d

Joining Objects in MySQL - JAVA

I used JOIN to join tables together and retrieve information. After retrieving objects I am adding that information to a table.
my query:
"SELECT L.LibPassport AS LibPassport,L.Object as LObject,G.Passport AS GPassport,"
+ "G.Object AS GObject,O.* FROM Orders AS O, Guest AS G, Librarian AS L WHERE O.Passport = G.Passport";
Firstly it gives me an error as Columns LObject not found then I changed all to only as Object , query worked smoothy but then its not adding all objects to List.
Method for sql is below:
public List<Object> getReport() {
List<Object> obj = new ArrayList<Object>();
Object x = null;
String query = "SELECT L.LibPassport AS LibPassport,L.Object as Object,G.Passport AS GPassport,"
+ "G.Object AS Object,O.*,O.Object AS Object FROM Orders AS O, Guest AS G, Librarian AS L WHERE O.Passport = G.Passport";
try {
state = conn.prepareStatement(query);
rs = state.executeQuery();
//Librarian
while(rs.next()) {
ByteArrayInputStream bais = new ByteArrayInputStream(rs.getBytes("Object"));
ObjectInputStream ois = new ObjectInputStream(bais);
x = ois.readObject();
obj.add(x);
ois.close();
bais.close();
}
}catch(SQLException | IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
and then I am accessing and differentiating using instanceof e.g.
if(obj.get(i) instanceof Transaction) {
a = (Transaction) obj.get(i);
fill.add(4,a.getBorrowDate());
fill.add(5,a.getReturnDate());
}
But its not getting all the objects, it either doesn't access or only 1 object. however the same query in mysql shows me all objects.
If you want further details please let me know.

Can we Get same return type , if we select only one column or more than one column in hibernate?

I made One Class for executing hibernate select operations my code is
working fine but i just need some help
I am passing hibernate select query from some other class to get the
result if my select query contains more than one column than I call the
method getListbylimit(String query,int limit) its returns
List but when my select query column contains only one than it
gives exception java.lang.String cannot be cast to
[Ljava.lang.Object;
for that I made second method List
getListForSingleColumn(String query) to get the result for single
column
is there any way to write method for this so that I can call only
one method. Rather my select query contain one column or more than one columns.
can I get return type List<Object[]> if I select only one column instead of List<String> so that I can use only one method for select operation
Here is my code
public class ContentDomain {
Session session;
public List<Object[]> getListbylimit(String query,int limit){
session = HibernateUtil.getSessionFactory().getCurrentSession();
/* session = HibernateUtil.getSessionFactory().openSession();
*/
List<Object[]> ls_ob = new ArrayList<Object[]>();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(query);
q.setMaxResults(limit);
ls_ob = (List<Object[]>)q.list();
}catch (HibernateException ex) {
if (tx != null) {
System.out.println("Exception in getList method " + ex);
tx.rollback();
ex.printStackTrace();
}
System.out.println("Exception getList tx open" + ex);
} finally {
session.close();
}
return ls_ob;
}
public List<String> getListForSingleColumn(String query){
session = HibernateUtil.getSessionFactory().getCurrentSession();
/* session = HibernateUtil.getSessionFactory().openSession();*/
List<String> ls_ob = new ArrayList<String>();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(query);
ls_ob = q.list();
}catch (HibernateException ex) {
if (tx != null) {
System.out.println("Exception in getList method " + ex);
tx.rollback();
ex.printStackTrace();
}
System.out.println("Exception getList tx open" + ex);
} finally {
session.close();
}
return ls_ob;
}
}
If you use native queries (session.createSQLQuery("yournnativequery)) you'll always get a List of Object[] with .list()... then it's easy to do a single private parsing method to handle both outputs.
You can replace ls_ob = (List<Object[]>)q.list(); with:
List<Object> result = q.list();
if (!result.isEmpty() && !(result.get(0) instanceof Object[])) {
ls_ob = result.stream().map(o -> new Object[] {o}).collect(Collectors.toList());
} else {
ls_osb = (List) result;
}
Basically, transform the single column query results manually.

Hibernate - Traversing createSQLQuery results and reading into appropriate object

I am pretty new to Hibernate / Java (JSF 2.0) and I am attempting to call a custom query and read the results into an object that I have created Logins. Logins has two setter functions, setLoginDate(Date date) and setUserId(Integer userId) my function looks like so, The issue I am having is how to transform the result set and read in the appropriate values into a temp loginList
public List<Logins> getUserLogins() {
Session session = getSessionFactory().openSession();
List<Logins> loginList = null;
Login temp = null;
try {
String SQL_QUERY = "SELECT login_date, user_id FROM user_logins";
Query query = session.createSQLQuery(SQL_QUERY);
List results = query.list();
for(ListIterator iter = results.listIterator(); iter.hasNext(); ) {
** THIS IS THE PART I AM NOT CLEAR ON ***
temp.setLoginDate(resutls.get(0));
temp.setUserId(results.get(1));
loginList.add(temp);
temp = null;
*****************************************
return loginList;
}
} catch(HibernateException e) {
throw new PersistanceDaoException(e);
} finally {
session.close();
}
}
missing part:
Object[] row = (Object[]) iter.next();
temp = new Login();
temp.setLoginDate(row[0]);
temp.setUserId(row[1]);
you may need to cast row[i] to your target object for example if login date is a date object: temp.setLoginDate((Date) row[0]);
for a better solution, try to use ResultTransformer
you can find more about ResultTransformer in Hibernate Docs.

Categories