Hibernate笔记_Mapping

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










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值