0

I don't know if the tittle is clear, but I am going to try to make myself as clear as possible. This is my scenario, I have a class called User:

@Entity(name="User_table")
public class User {
    @Id @GeneratedValue
    int userId;

    String userName;

    String userMessage;


//    public User(String userName, String userMessage)
//      {
//          this.userName= userName;
//          this.userMessage = userMessage;
//      }
//  public User(){}

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserMessage() {
        return userMessage;
    }
    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

}

Related to that table:

  mysql> select * from User_table;
+--------+-------------+
| userId |  | userName |
+--------+-------------
|     71 | | Dani     |
|     72 | | Dani     |
+--------++------------
2 rows in set (0.00 sec)

And what I want is to select all the objects from User_table, where userName = Dani. So, what I do is this:

public List<Object> HotelesNombre(String name) {

        int i = 0;
        User user = null;
        SessionFactory sf = open();
        Session ss = sf.openSession();
        ss.beginTransaction();
        Query query = ss.createQuery("select userId, userName from User_table where userName = :id ");
        query.setParameter("id", name);
        List<Object> list = query.list();
        if (list.size() != 0) {
            ss.getTransaction().commit();
            ss.close();
            return list;
        } else {
            ss.getTransaction().commit();
            ss.close();
            return null;
        }
    }

As you can see, I use List instead of List because I am selecting a part of the object User (not the whole) and List wouldn't work.

So, for testing, in the main class I have:

public class HibernateMain {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int status;

        int i=0;

        Manager manager = new Manager();

        status = manager.creaUsuario("Dani", "pollo");

        //User user = manager.buscaHotel(71);

        List<Object> list = manager.HotelesNombre("Dani");

        System.out.println(list.get(0).getUserName());

        if (list.size() >0){

            for (Object v : list){


                System.out.println(v.getUserName());
            i++;

            }



        }


//      if (user !=null){
//      
//      System.out.println(user.getUserName());
//      }

    }

}

I have problem in the lines: System.out.println(v.getUserName()); and System.out.println(v.getUserName()); I can't use the methods in the User Class as v is not a User, so.... how could I do what I want¿? Thank you very much.

1 Answer 1

1

What you get back for such a query is a List<Object[]>, i.e. a list which contains arrays of objects. Each array is a row returned by the query. And since the query selects userId and userName, each array contains two elements, the user ID (an Integer instance), and the user name (a String instance).

Note that, unless you have a huge number of columns, representing a massive amount of information (i.e. blobs), in this table, what you're doing is a premature optimization. You'd better simply use select u from User u where ..., and get back a List<User>.

Sign up to request clarification or add additional context in comments.

7 Comments

I can't do that,if I do that: </br>Query query = ss.createQuery("select userId, userName from User_table where userName = :id "); query.setParameter("id", name); List<User> list = query.list(); I got this error: <br/> [Ljava.lang.Object; cannot be cast to org.arpit.javapostsforlearning.User <br/> This is the reason I use List<Object[]>
You can't do what? Have you read my answer. It precisely says that such a query does not return a List<User>, but a List<Object[]>. Re-read it. If you want a List<User>, the query must retrieve users: select u from User u ...
Can you please write the whole query¿? I think that the select u from User u where..... is confusing me, I don't know if you mean User or User_table, thankss
I didn't notice you had given a name User_table to your entity. So yes, it should be User_table. That makes things pretty unreadable and confusing, though. Why not use the default name: User.
I have written everything in my answer. If you want a List<User>, use select u from User_table u. NOT select userId, userName. Such a query is valid but it doesn't return User instances. It returns arrays of objects, each array containing a user ID and a user name. I don't know how I could be clearer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.