1

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

Customer表有两列:id、name。

Order表有两列:id、customer_id

这两个表之间存在一对一的关系

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

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

}
4

2 回答 2

1

ORDER BY 是一个 SQL 关键字。也许表名使解析器感到困惑。我建议您重命名它并重试。

于 2012-04-14T12:22:30.800 回答
1

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

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

但如果您仍在开发中,请更改表名和列名以避免使用 SQL 关键字。

于 2012-04-14T12:34:24.157 回答