Hibernate保存关系表

时间:2012-04-14 12:20:56

标签: java hibernate annotations

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

  

Customer 表有两列:id,name。

     

订单表有两列: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();
    }

}

2 个答案:

答案 0 :(得分:1)

ORDER BY是一个SQL关键字。表名可能会使解析器混乱。我建议您重命名并重试。

答案 1 :(得分:1)

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

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

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