使用jpa从db输出数据

时间:2014-11-11 18:33:41

标签: java jpa

您好我试图使用jpa从db打印所有客户,但我得到的输出采用以下格式:model.Customer@3d47d922, model.Customer@5f6f2271, model.Customer@6facbae5

继承人使用的方法:

public List<Customer> getAllCustomers()
    {
        EntityManager em = null;
        List<Customer> resultList = new ArrayList<Customer>();
        try
        {
            em = JpaUtil.getFactory().createEntityManager();
            TypedQuery<Customer> query = em.createQuery("select p from Customer p", Customer.class);
            resultList = query.getResultList();

        }
        finally {

            JpaUtil.closeQuietly(em);
        }
        return resultList; 

Heres servlet我试图输出客户:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    CustomerDAO dao = new CustomerDAO();    

    response.getWriter().println(dao.getAllCustomers());

继承我的模特课:

    @Entity
    public class Customer {

    @Id
    @SequenceGenerator(name = "my_seq", sequenceName = "seq1", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")
    private Long id;


    private String first_name;


    private String surname;
    private String code;
    public enum Customertype{Private, Corporate};
    @Enumerated(EnumType.STRING)
    private Customertype customer_type;


    public Customer() {}


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return first_name;
    }

    public void setFirstName(String firstname) {
        first_name = firstname;
    }


    public String getSurname() {
        return surname;
    }


    public void setSurname(String surName) {
        surname = surName;
    }


    public Customertype getCustomertype() {
        return customer_type;
    }


    public void setCustomertype(Customertype customerType) {

        this.customer_type = customerType;
    }


    public String getCode() {
        return code;
    }


    public void setCode(String code) {
        this.code = code;
    }



}

2 个答案:

答案 0 :(得分:4)

您需要覆盖客户类中的toString() method。每当您尝试使用println()打印对象时,都会调用toString()方法。

Object类中toString()的默认行为是打印类的名称,@符号和对象的hascode。这就是你所看到的。

例如

public String toString(){
    return this.getFirstName();
}

答案 1 :(得分:1)

您需要覆盖类中的toString方法,因为它会以您可以理解的可读格式为您提供有关对象的明确信息。

覆盖toString

的优点
  

帮助程序员记录调试Java程序

     

由于 toString 是在 java.lang.Object 中定义的,并且没有提供有价值的信息,所以它是      为子类重写它的好习惯。