Hibernate笔记_Mapping
来源:互联网 发布:软件的功能性 编辑:程序博客网 时间:2024/05/24 01:43
1. 对Mapping的最好定义:
The mappings are applied to express the various different ways of forming associations in the underlying tables; there
is no absolutely correct way to represent them.
意思是不是:对象之间的关联 + 描述映射的annotation就可以推导出数据库结构。
2. mappedBy:
- The mappedBy attribute is mandatory on a bidirectional association and optional (being implicit)
on a unidirectional association.
@Entity(name = "Email2")public class Email { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; @Column String subject; @OneToOne(mappedBy = "email") Message message; public Email() { }}@Entity(name = "Message2")public class Message { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; @Column String content; @OneToOne Email email; public Message() { }}
意思是:
1)Email 是主表,Message是从表。即Message表中有一外键是email_id。
2)(从表是关系的所有者)Only changes to the owner of an association will be honored in the database.
意思是 message.setEmail(email);才会在数据库中创建主外键关系。完整的测试代码如下:
@Test public void testImpliedRelationship() { Long emailId; Long messageId; Session session = SessionUtil.getSession(); Transaction tx = session.beginTransaction(); Email email = new Email("Inverse Email"); Message message = new Message("Inverse Message"); // email.setMessage(message); message.setEmail(email); session.save(email); session.save(message); emailId = email.getId(); messageId = message.getId(); tx.commit(); session.close(); assertEquals(email.getSubject(), "Inverse Email"); assertEquals(message.getContent(), "Inverse Message"); assertNull(email.getMessage()); assertNotNull(message.getEmail()); session = SessionUtil.getSession(); tx = session.beginTransaction(); email = (Email) session.get(Email.class, emailId); System.out.println(email); message = (Message) session.get(Message.class, messageId); System.out.println(message); tx.commit(); session.close(); assertNotNull(email.getMessage()); assertNotNull(message.getEmail()); }
要点:
Table 4-1 shows how you can select the side of the relationship that should be made the owner of a bidirectional
association. Remember that to make an association the owner, you must mark the other end as being mapped by the other.
Table 4-1. Marking the Owner of an Association
- Hibernate笔记_Mapping
- Hibernate笔记
- Hibernate 笔记
- Hibernate笔记
- Hibernate笔记
- Hibernate笔记
- hibernate笔记
- Hibernate笔记
- Hibernate笔记
- hibernate笔记
- hibernate笔记
- Hibernate笔记
- hibernate 笔记
- Hibernate笔记
- Hibernate笔记
- Hibernate 笔记
- Hibernate 笔记
- Hibernate 笔记
- HTTP协议详解
- 三分天下的互联网保险,后来者还有无机会?
- WPF仿百度Echarts人口迁移图
- 打开MySQL数据库远程访问的权限
- 运用软件配置管理加强风险管理
- Hibernate笔记_Mapping
- HTTP协议状态码的含义
- GitHub
- android安全退出应用
- 机器学习 画出超平面w.T*x+b
- 排序算法(3)——选择排序
- 调用自身function造成的死循环
- linux uniq,sort
- Android 与 IOS的UUID的区别