gpt4 book ai didi

java - Hibernate:映射映射异常

转载 作者:行者123 更新时间:2023-12-01 13:11:04 26 4
gpt4 key购买 nike

我尝试通过Map接口(interface)映射一对二多关系。

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

异常

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
}

最佳答案

请尝试此代码:

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

}

关于java - Hibernate:映射映射异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22865670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com