Hibernate:映射映射异常

时间:2014-04-04 14:33:01

标签: java hibernate

我尝试通过Map界面映射一对多关系。

问题:我遇到了一个奇怪的异常

异常

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at ...
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "Order"

导致异常的SQL查询:(show_sql = true)

Hibernate: insert into Order (customer_id, number, id) values (?, ?, ?)

代码:

public static void main(String[] args) {
    Session createSession = HibernateUtil.getSessionFactory().openSession();
    createSession.beginTransaction();

    final Customer customer = new Customer();
    Map<String, Order> orders = new HashMap<String, Order>() {{
        put("one", new Order("one", customer));
        put("two", new Order("two", customer));
        put("three", new Order("three", customer));
    }};
    customer.setOrders(orders);
    for (Order order : orders.values())
        createSession.save(order);
    createSession.save(customer);

    createSession.getTransaction().commit(); //HERE THE EXCEPTION COMES
    createSession.close();
}

实体:

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

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

    // + getters & setters
}

@Entity
public class Order {

    @Id
    @GeneratedValue
    private Integer id;

    private String number;

    @ManyToOne
    private Customer customer;

    //+ Constructors, getters & setters
}

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

public static void main(String [] args){

Session createSession = HibernateUtil.getSessionFactory().openSession();
createSession.beginTransaction();

final Customer customer = new Customer();
Map<String, Order> orders = new HashMap<String, Order>() {{
    put("one", new Order("one", customer));
    put("two", new Order("two", customer));
    put("three", new Order("three", customer));
}};

for (Order order : orders.values())
    order.setCustomer(customer);

customer.setOrders(orders);
createSession.save(customer);

createSession.getTransaction().commit(); //HERE THE EXCEPTION COMES
createSession.close();

}