How to print actual data from list of objects? - java

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

Related

ClassCastException with java List Iterator with Generics

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
}

CYPHER QUERY :-Change Arrayreturned by collect(n.name) in cypher query to Arraylist (util)

Neo4j cypher query collect() return Array in result. In order to iterate it we need it to add in arrayList. The previous process we used is not helping us and throwing an exception.
PREVIOUS CODE:-
public String GettingCurrentDate() {
Connection connect = null;
String query=null;
try {
connect = graphdbConnect();
Statement stmt = connect.createStatement();
query="match(n:learner) "
+ " return collect(n.name) as ids";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query.toLowerCase());
while(rs.next()){
Array idsList=rs.getArray("ids");
System.out.println("idsList :: "+idsList);
ArrayList<String> userIds = new ArrayList<>();
String[] userIdsArray = (String[])rs.getArray("ids").getArray();
for(String id : userIdsArray) {
userIds.add(id);
System.out.println(userIds+"------userId");
}
}
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(connect!=null) {
try {
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "sucess";
}
This code is getting exception java.sql.SQLFeatureNotSupportedException: get array
Question:- HOW WILL WE GET THE DATA FROM COLLECT() function and iterate it
Have you checked to see the actual object returned by
resultSet.getObject("ids")
If it's like user defined procedures, collections in Cypher get returned as ArrayLists, so try casting the returned object to an ArrayList and see if that works for you.
Cast Object to ArrayList
Object idsList=rs.getObject("ids");
System.out.println("idsList :: "+idsList);
ArrayList<String> userIds = (ArrayList<String>) idsList;
System.out.println("List2 Value: "+userIds);

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.

How to save multiple String element from List<String> into a db using JPA?

I tried so far the below code:
Session session = null;
Query query1 = null;
Query query2 = null;
String[] parts = userId.split("=");
userId = parts[1];
parts = userId.split(" ");
userId = parts[0];
int intIdUser = Integer.parseInt(userId);
try {
session = getSession();
UserCountry userCountry = new UserCountry();
UserLanguage userLanguage = new UserLanguage();
for (String s : user_country) {
userCountry.setUserId(intIdUser);
userCountry.setCountryId(Integer.parseInt(s));
session.getTransaction().begin();
session.persist(userCountry);
session.getTransaction().commit();
}
for (String s : user_language) {
userLanguage.setUserId(intIdUser);
userLanguage.setLanguageId(Integer.parseInt(s));
session.getTransaction().begin();
session.persist(userLanguage);
session.getTransaction().commit();
}
}
catch(Exception e) {
logger.error("Exception while fetching for countryId: "+userId, e);
throw new PlRuntimeException(e.getMessage());
}
finally {
if(session !=null)
session.close();
}
But the for (String s : user_country) and for (String s : user_language) loops are saving just first element on the list user_country and user_language.
How to make it save the other elements on the list?
Thanks for advice.
You are continuously updating the same object.
You just need to create the UserCountry and UserLanguage inside the loop. As of now you are creating outside the loop. Just move them inside the loops.
For ex :
for (String s : user_country) {
UserCountry userCountry = new UserCountry();
userCountry.setUserId(intIdUser);
userCountry.setCountryId(Integer.parseInt(s));
session.getTransaction().begin();
session.persist(userCountry);
session.getTransaction().commit();
}

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