我在Flight(Parent)和Airline(Child)之间有一个单向的一对一映射,下面是我的代码-
public class Airline {
..
@OneToOne(cascade=CascadeType.ALL)
Flight flight;
}
Flight没有任何
Airline
引用,该引用具有ID,分别命名为getter和setter。我坚持
airline
和级联启用。 Flight flight= new Flight();
flight.setName("flight2");
Airline airline= new Airline();
airline.setName("Air India");
airline.setFlight(flight);
Session session=sessionFactory.openSession();
session.saveOrUpdate(airline);
session.saveOrUpdate(flight);
这引发了异常MySQLSyntaxErrorException:“字段列表”中的未知列“ flights_id”。所以我加了
@JoinColumn
这对答案很有用。编辑 - -
但是我做了一个没有mapbyby的双向(即两个单向关联),并且没有在第二个表中应用@joinColumn
public class Airline {
@JoinColumn("flight_ref_id")
@OneToOne(cascade=CascadeType.ALL)
Flight flight;
}
public class Flight {
@OneToOne(cascade=CascadeType.ALL)
Airline airline;
}
和
airline.setFlight(flight);
flight.setAirLine(airline)
Session session=sessionFactory.openSession();
session.saveOrUpdate(airline);
现在没有例外,即使Flight.it中也没有
@joincolumn
,它为何创建列airline_id
呢?mysql> select * from Airline;
+----+-----------+---------------+
| id | name | flight_ref_id |
+----+-----------+---------------+
| 1 | Air India | NULL |
+----+-----------+---------------+
1 row in set (0.00 sec)
mysql> select * from Flight;
+----+--------+------------+
| id | name | airline_id |
+----+--------+------------+
| 1 | Del-NJ | 1 |
+----+--------+------------+
并且在db
flight_ref_id
中为null。为什么? 最佳答案
您需要添加@JoinColumn批注以添加更多列作为排期外键
public class Airline {
..
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "flights_id", nullable = false)
Flight flight;
}