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();    }


可以通过这段代码,给 Linda 换一个老公,但能为 John 换一个妻子吗?

hushand.setWife 这个方法没有任何作用,持久化时并不会做任何处理,

因为 hushand 表中没有 wifeId 字段,这样就是 mappedBy 的意思。


再强调一遍,只是看着像在操作对象,实质还是关系型。


提醒1:

使用 mappedBy 时,注意不要调用被维护方的 setter。



然后我们来谈谈 mappedBy 第二个问题。



两条记录可以拥有相同的 husbandId, 这不就破坏了 OneToOne 吗?


好吧,mappedBy 暂时分析到这。





0 0