在Hibernate中使用Map无法正常工作

时间:2014-08-19 16:59:13

标签: java hibernate

我正在尝试使用java.util.Map创建一个简单的程序。我创建了一个Customer实体类,其中包含Order类的映射。这是我的Java类:

Customer.java

@Entity
public class Customer {
    @Id
    @GeneratedValue
    private Integer id;

    @OneToMany(mappedBy = "customer")
    @MapKey(name = "orderNumber")
    private Map<String, Order> orders;
}

Order.java

@Entity
@Table(name="TB_ORDER")
public class Order {
    @Id
    @GeneratedValue
    private Integer id;
    private String orderNumber;
    @ManyToOne
    private Customer customer;
}

这是我的程序试图用一些订单保存客户,然后我试图显示保存的数据:

public class AppTest {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        saveCustomer(session);
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        showCustomer(session);
        HibernateUtil.getSessionFactory().close();
    }

    private static void showCustomer(Session session) {
        session.getTransaction().begin();
        List<Customer> list = session.createQuery("from Customer").list();
        for (Customer customer : list) {
            System.out.println("customer id : "+customer.getId()+ ", customer orders : "+customer.getOrders());
        }
        session.getTransaction().commit();
    }

    private static void saveCustomer(Session session) {
        session.getTransaction().begin();
        Customer customer = new Customer();
        Order order = new Order();
        order.setCustomer(customer); order.setOrderNumber("100");
        Map<String, Order> map = new HashMap();
        map.put("100", order);
        customer.setOrders(map);
        session.save(customer); session.save(order);
        session.getTransaction().commit();
    }
}

运行程序后,Hibernate在DDL&amp; DML命令:

Hibernate: create table Customer (id number(10,0) not null, primary key (id))
Hibernate: create table TB_ORDER (id number(10,0) not null, orderNumber varchar2(255 char), customer_id number(10,0), primary key (id))
Hibernate: alter table TB_ORDER add constraint FK_qr7tjivmclv5trf0sbwxki4v foreign key (customer_id) references Customer

Hibernate: insert into Customer (id) values (?)
Hibernate: insert into TB_ORDER (customer_id, orderNumber, id) values (?, ?, ?)
Hibernate: select customer0_.id as id1_0_ from Customer customer0_
customer id : 1, customer orders : null

Hibernate仅生成单个select查询以获取客户详细信息,但未从TB_ORDER表中获取任何数据。因此,当我尝试从客户处获得订单时,我将变为空。请告诉我这段代码中的错误在哪里。

2 个答案:

答案 0 :(得分:2)

看起来你错过了@JoinColumn注释,通过它可以告诉谁是关系的拥有者。出于这个原因,我认为您应该更改类顺序:

@Entity
@Table(name="TB_ORDER")
public class Order {
    @Id
    @GeneratedValue
    private Integer id;
    private String orderNumber;
    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;
}

应该可以正常工作。

答案 1 :(得分:0)

您还必须使用@MapKeyJoinColumn,以便更好地在pojo中初始化Map并重试。

private Map<String, Order> orders =new Map<String, Order>();