【发布时间】:2017-01-13 08:08:16
【问题描述】:
我有两个实体 PointOfInterest(从这里称为 POI)及其地址。我想用两者之间的共享主键定义一对一的双向映射,POI 作为所有者实体。我正在使用 postgreSQL DB,POI 表的 POIId 为 PK,由 DB 中定义的序列生成器生成。地址表有 POIId 列,它是地址表的 PK,也是 POI 表的 POIId 列的 FK,以及它自己的其他列。
**PointOfInterest.java**
@Entity
@Table(name = "\"POI\"")
public class PointOfInterest implements Serializable {
private static final long serialVersionUID = -5406785879200149642L;
@Id
@Column(name="\"POIId\"", nullable=false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="poi_seq_poiid_generator")
@SequenceGenerator(name = "poi_seq_poiid_generator", sequenceName = "poi_seq_poiid", allocationSize=1)
private Long poiId;
@OneToOne(mappedBy = "poi",cascade = CascadeType.PERSIST)
private Address address;
//Other fields
-----------------------------------------------------------------
**Address.java**
@Entity
@Table(name="\"Address\"")
public class Address implements Serializable{
private static final long serialVersionUID = -7146133528411371107L;
@Id
@GeneratedValue(generator="sharedPrimaryKeyGenerator")
@GenericGenerator(name="sharedPrimaryKeyGenerator",strategy="foreign",parameters = @Parameter(name="property", value="poi"))
@Column(name="\"POIId\"")
private Long poiId;
@OneToOne
@PrimaryKeyJoinColumn
private PointOfInterest poi;
在使用 session.saveOrUpdate(poi) 保存 POI 对象之前。我实例化并设置 POI 对象的所有其他属性。然后,从我的逻辑中的单独方法获取地址对象并执行类似的操作。
PointOfInterest poi = methodCallToGetPOI();
Address address = methodCallToGetAddress();
poi.setAddress(address);
address.setPOI(poi);
//Send POI object to DB layer to an appropriate method which does:
session.saveOrUpdate(poi);
session.flush();
当我看到生成的查询时,我看到如下内容:
Hibernate:
select
nextval ('poi_seq_poiid')
Hibernate:
insert
into
"POI"
("CreatedBy", "CreatedTime", "LocationGeographic", "ModifiedBy", "ModifiedTime", "Name", "POICode", "Radius", "POIType", "POIId")
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
因此,显然 hibernate 并没有在地址表中进行插入语句。我在互联网上到处搜索并比较了我的映射,它们似乎是正确的。但是,地址表中没有插入任何行。当我调试流程时,我发现地址对象正在被实例化和填充。请帮我弄清楚这是为什么。我能想到的唯一原因是我使用了序列生成器,并且在互联网上的所有示例和代码 sn-ps 中,每个人都使用了 hibernate 的自动生成策略,那么,是因为这个吗?我不能使用自动生成密钥,我只能使用我的数据库序列。如果这些注释不起作用,请提出一些替代方案。
我正在使用 Spring 和 Hibernate 以及 Spring 框架版本 4.0.5.RELEASE 以及从 org.springframework.orm.hibernate4.LocalSessionFactoryBean 获得的会话工厂和从 org.springframework.orm.hibernate4.HibernateTransactionManager 获得的事务管理器。
【问题讨论】:
标签: java spring hibernate one-to-one bidirectional