gpt4 book ai didi

java - Hibernate保存关系表

转载 作者:行者123 更新时间:2023-11-30 04:49:32 26 4
gpt4 key购买 nike

我有一个具有以下表结构的数据库...

The Customer table has two columns : id, name.

The Order table has two columns: id, customer_id

There is a one-to-one relation between these two tables

当我运行下面给出的代码时,出现以下异常:

Hibernate: insert into customer (name) values (?)
Hibernate: insert into order (customer_id) values (?)
05:02:46,374 WARN [main] JDBCExceptionReporter:233 - SQL Error: 0, SQLState: 42601
05:02:46,379 ERROR [main] JDBCExceptionReporter:234 - ERROR: syntax error at or near "order"

这是我的代码。有人可以帮忙解释一下问题的原因吗...

@Entity
@Table(name = "customer")
public class Customer implements Serializable {


public Customer() {
}

private long id;
private String name;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", insertable = false, updatable = false, nullable = false)
public long getId() {
return id;
}

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

@Column(name = "name")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


@Entity
@Table(name = "order")

public class Order implements Serializable {
public Order() {
}

public Order(Customer customer) {
this.customer = customer;
}

private long id;
private Customer customer;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", insertable = false, updatable = false, nullable = false)
public long getId() {
return id;
}

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

@OneToOne(cascade = { CascadeType.ALL })
@JoinColumn(name = "customer_id")
public Customer getCustomer() {
return customer;
}

public void setCustomer(Customer customer) {
this.customer = customer;
// setCustomerId(customer.getId());
}
}

public static void main(String[] args) {

Customer cm = new Customer();
cm.setName("John");

Order ord = new Order(cm);

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Transaction transaction = null;

try {
transaction = session.beginTransaction();
session.save(ord);
transaction.commit();
}
catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
}
finally {
session.close();
}

}

最佳答案

order 是一个 SQL 关键字。如果您无法更改数据库名称,请尝试使用:

@Table( name = "\"order\"" )

但如果您仍处于开发阶段,请更改表和列名称以避免使用 SQL 关键字。

关于java - Hibernate保存关系表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153567/

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