简体   繁体   English

将输出作为对象而不是字符串

[英]Getting the output as object instead of string

In the following program I am getting the output as Hibernate.UserDetails@224b4d61 在下面的程序中,我得到的输出为Hibernate.UserDetails@224b4d61

How should i fix this? 我该如何解决?

The following are the two programs I am using and I need to print the username 以下是我正在使用的两个程序,我需要打印username

HibernateTest: HibernateTest:

public class HibernateTest {
    public static void main(String[] args) 
    {
        SessionFactory sessionfactory = new Configuration().configure("Hibernate/hibernate.cfg.xml").buildSessionFactory();
        Session session = sessionfactory.openSession();
        session.beginTransaction();

        Criteria criteria = session.createCriteria(UserDetails.class);
        criteria.add(Restrictions.eq("UserName","User5"));
        List<UserDetails> user =(List<UserDetails>) criteria.list();
        session.getTransaction().commit();
        session.close();
        for(UserDetails u : user)
        {
            System.out.println("Name of User is : "+u);
        }
    }
}

UserDetails: 用户详细信息:

@Entity
public class UserDetails 
{
    @Id @GeneratedValue(strategy=GenerationType.AUTO) 
    private int UserId;
    private String UserName;

    public int getUserId() {
        return UserId;
    }
    public void setUserId(int userId) {
        UserId = userId;
    }
    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }
}

您当前正在尝试打印整个UserDetails对象,但是我认为您正在尝试仅打印用户名...

System.out.println("Name of User is : " + u.getUserName());

You should override the toString method . 您应该重写toString方法

@Entity
public class UserDetails 
{
    @Id @GeneratedValue(strategy=GenerationType.AUTO) 
    private int UserId;
    private String UserName;

    public int getUserId() {
        return UserId;
    }
    public void setUserId(int userId) {
        UserId = userId;
    }
    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }

    public String toString() {
      return getUserName() + " (id = " + getUserId().toString()  + ")"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM