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