我有两个简单的表Customers
和Orders
,oneToMany
到customer
表的关系为Orders
。
这是我的Customers.java
@Entity
public class Customers implements Serializable {
@Id
@GeneratedValue
private int cID;
private String name;
private String email;
// getter and setters
}
这是Orders.java
:
@Entity
public class Orders implements Serializable {
@Id
@GeneratedValue
private int orderID;
private int cId;
@Column(nullable = false)
@Temporal(TemporalType.DATE)
private Date date;
@ManyToOne(cascade = CascadeType.ALL)
private Customers customers;
// getter and setters
}
现在,我要在Orders
表中插入两条记录:
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Orders orders1 = new Orders();
Orders orders2 = new Orders();
Customers customer = new Customers();
customer.setName("c1");
customer.setEmail("abc@gmail.com");
orders1.setDate(new Date());
orders2.setDate(new Date());
orders1.setCustomers(customer);
orders2.setCustomers(customer);
session.save(orders1);
session.save(orders2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
这是控制台中的结果:
Hibernate: alter table Orders drop foreign key FK_hmbx2rg9tsgqikb3kodqp90c4
Hibernate: drop table if exists Customers
Hibernate: drop table if exists Orders
Hibernate: create table Customers (cID integer not null auto_increment, email varchar(255), name varchar(255), primary key (cID))
Hibernate: create table Orders (orderID integer not null auto_increment, cId integer not null, date date not null, customers_cID integer, primary key (orderID))
Hibernate: alter table Orders add constraint FK_hmbx2rg9tsgqikb3kodqp90c4 foreign key (customers_cID) references Customers (cID)
Feb 24, 2015 1:58:52 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Customers (email, name) values (?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
这是结果表:
为什么cID
表中的Orders
(这是customers
的外键引用)是0
?
应为1
。
答案 0 :(得分:1)
它认为orders
表customers_cId
是customers
表的实际外键引用列。由于您没有明确地给出任何列名,因此通过连接两个实体的变量,内部将列名称作为customers_cId
。来自customers
实体的orders
和cId
的{{1}}。
只是为了验证您可以尝试使用customers
注释提供其他名称。
@JoinColumn
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="order_cId")
private Customers customers;
表中的cId
只是一个独立的列,因为您没有为其设置任何值,它将默认值设为orders
。尝试为其设置一些随机值。