Hibernate 学习记录 3
来源:互联网 发布:淘宝卖家推广软件 编辑:程序博客网 时间:2024/06/12 00:54
这篇文章,将介绍 Hibernate 中的 mappedBy。
在 Husband 类中添加如下属性和方法:
@OneToOne(mappedBy = "husband") private Wife wife; public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; }
现在我们可以通过 Husband 访问 Wife 了:
public static void main(final String[] args) throws Exception { String husbandId = "89c0eaf4-124c-4881-b14e-01bf7a7f7bf5"; Husband husband = HusbandDao.getHusbandById(husbandId); System.out.print(husband.getWife().getName()); HibernateUtil.close(); }
这个很棒,一个 mapped 就可以双向访问了。
但真的足够了吗?
mappedBy 意味着 husband 就是被维护的一方,
意味着 Husband 类的功能是残缺的。
public static void main(final String[] args) throws Exception { String wifeId = "60e83ecf-f263-45f5-b95f-24ec8ea2ccf6"; Wife Linda = WifeDao.getWifeById(wifeId); String husbandId = "845ee7b0-42e3-4614-a1ee-8a475209b070"; Husband John = HusbandDao.getHusbandById(husbandId); Linda.setHusband(John); WifeDao.saveOrUpdate(Linda); HibernateUtil.close(); }
hushand.setWife 这个方法没有任何作用,持久化时并不会做任何处理,
因为 hushand 表中没有 wifeId 字段,这样就是 mappedBy 的意思。
再强调一遍,只是看着像在操作对象,实质还是关系型。
提醒1:
使用 mappedBy 时,注意不要调用被维护方的 setter。
然后我们来谈谈 mappedBy 第二个问题。
两条记录可以拥有相同的 husbandId, 这不就破坏了 OneToOne 吗?
好吧,mappedBy 暂时分析到这。
0 0
- hibernate学习记录3
- Hibernate 学习记录 3
- Hibernate学习记录
- hibernate学习记录
- hibernate缓存学习记录
- hibernate学习记录1
- hibernate学习记录2
- hibernate学习记录5
- hibernate学习记录6
- hibernate学习记录7
- hibernate学习记录8
- Hibernate 学习记录
- Hibernate 学习记录 2
- Hibernate 学习记录 4
- Hibernate学习记录1
- Hibernate学习记录2
- 关于Hibernate学习记录
- Hibernate学习记录3 Hibernate 配置多数据源
- Python学习笔记17:标准库之数学相关(math包,random包)
- windows进程间通信
- Centos6.4中编译安装MPlayer
- goldendict 下载及使用 ubuntu下
- php操作xml并将其插入数据库
- Hibernate 学习记录 3
- 百度面试题之 循环链表求出最短的包括所有元素的字串长度
- 黑马程序员——IO流复制文件
- 讨厌的代码
- C语言_循环结构
- 步行者vs开拓者忱
- masm对于 mov ax,[0] 的解决
- 八大排序算法
- Linux复制指定目录及子目录下特定类型的文件