Spring data jpa @OneToOne

作业里遇到这样一个scenario:要求把entityA的某些attributes拆分出来专门做一个entityB,并且做好mapping。每次更新entityA时,数据库的两张表都会更新。并能够对entity的所有表进行查询。---注意这个和embedded的区别, embedded只有一张表!。

 

@OneToOne表示两个entity一一对应 --- 两个entity就意味着数据库里有两张表!

@OneToOne defines a one-to-one relationship with another entity. 

@JoinColumn indicates the entity is the owner of the relationship: the corresponding table has a column with a foreign key to the referenced table.

@mappedBy indicates the entity is the inverse of the relationship.

 

一个越南小哥写的挺好的。他做的Hello Koding网站也不错

另一个wife-husband的例子非常生动。创建wife时husband表自动创建。而且wife husband都有dao(repository类),创建好wife后就大家也可以独立访问所有的husbands了。

extra example

 

P.S. 1 .

建entity时 primary key的选择

string是否可以当key? 有的说可以,只要不是generated value就可以了。

另一个stackoverflow页面说,GeneratedValue id只能是int short long,string类型的只能是uuid。这两种回答是consistent的。

P.S. 2.

Respository类的方法要改一下。

比如以前attributeX现在被归类为EntityB(e.g. EntityA, UserInfo, EntityB, UserAddressInfo),

findByAttributeX() 要改为findByEntityBAttributeX()

 

posted @ 2017-12-21 03:54  aureole420  阅读(414)  评论(0)    收藏  举报