我正在尝试通过hibernate实现订单管理系统,我不是很熟悉。异常要求我在我的程序尝试中手动执行sql和hibernate一样,并且成功了。我不知道是什么问题。可能是设计问题。数据库是这样的:
ORDER在ITEM表中有一个指向ITEM_ID的外键ITEM_ID,它是一对多的关系,另一个外键CLIENT_ID指向CLINET表中的CLIENT_ID。 带有注释的三个实体定义写为
@Table(name = "ITEM")
public class Item implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ITEM_ID", unique = true, nullable = false)
private int item_id;
@Column(name = "NAME")
private String name;
@Column(name="CATEGORY")
private String category;
@Column(name="UNIT")
private String unit;
@Column(name="PRICE")
private double price;
//getters and setters
}
@Entity
@Table(name="CLIENT")
public class Client implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CLIENT_ID", unique = true, nullable = false)
private int client_id;
@Column(name="CLIENT_NAME")
private String client_name;
//getters and setters
}
@Entity
@Table(name="ORDER")
public class Order {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ORDER_ID", unique = true, nullable = false)
private int order_id;
@ManyToOne(cascade = CascadeType.PERSIST,targetEntity=Client.class)
@JoinColumn(name = "CLIENT_ID", nullable = false)
private Client client;
@ManyToOne(cascade = CascadeType.PERSIST,targetEntity=Item.class)
@JoinColumn(name = "ITEM_ID", nullable = false)
private Item item;
@Column(name="QUANTITY")
private double quantity;
@Temporal(TemporalType.DATE)
@Column(name = "ORDER_DATE")
private Date order_date;
//getters and setters
}
订单数据插入功能如下:
public static void insertNewOrder(Item item,Client client, double quantity, Date date){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Order order = new Order();
order.setItem(item);
order.setClient(client);
order.setQuantity(new Double(quantity));
order.setOrder_date(date);
session.save(order);
session.getTransaction().commit();
session.close();
}
这是我的例外:
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER (CLIENT_ID, ITEM_ID, ORDER_DATE, QUANTITY) values (1, 1, '2013-11-12', 1.4' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER (CLIENT_ID, ITEM_ID, ORDER_DATE, QUANTITY) values (1, 1, '2013-11-12', 1.4' at line 1
我手动尝试过这个sql,并且确实成功插入了。我找不到问题所在的任何线索。请帮忙。
答案 0 :(得分:5)
ORDER
是一个MySQL关键字。如果必须将它用作表名,则需要在反引号中包装每个引用。
SELECT * FROM `ORDER`...
我建议您将表名称设置为不冲突的内容