VB_
VB_

Reputation: 45682

Hibernate: mapping map exception

I try to map one-2-many relationship via Map interface.

Problem: I got a weird exception

Exception

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 query which cause rhe exception: (show_sql=true)

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

Code:

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();
}

Entities:

@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
}

Upvotes: 0

Views: 116

Answers (1)

user3489875
user3489875

Reputation: 457

Please try this code:

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();

}

Upvotes: 1

Related Questions