【转载】使用Hibernate Annotations 维护多对多关系的心得

 

说明
        在HibernateAnnotations中通过@ManyToMany注解可定义多对多关联。同时,也需要通过注解@JoinTable描述关联表和关联条件。对于双向关联,其中一端必须定义为owner,另一端必须定义为inverse(在对关联表进行更性操作时这一端将被忽略)。被关联端不必也不能描述物理映射,只需要一个简单的mappedBy参数,该参数包含了主体端的属性名,这样就绑定了双方的关系。
      上周六去电影院圆了儿时的梦想,看了变形金刚,超棒的一部片子 ^_^。那么就以剧院和观众为例讲解吧。
如何制作PO
1)找到CUBE--需要引入哪些类:

None.gif import  java.util.ArrayList;
None.gif import  java.util.List;
None.gif import  javax.persistence.CascadeType;
None.gif import  javax.persistence.Entity;
None.gif import  javax.persistence.FetchType;
None.gif import  javax.persistence.JoinColumn;
None.gif import  javax.persistence.JoinTable;
None.gif import  javax.persistence.ManyToMany;
None.gif import  javax.persistence.Table;
None.gif import  org.hibernate.annotations.Cache;
None.gif import  org.hibernate.annotations.CacheConcurrencyStrategy;

2)找到汽车人--主体端:

ExpandedBlockStart.gif/**
InBlock.gif * Theater
InBlock.gif * @author allen
ExpandedBlockEnd.gif */
None.gif@SuppressWarnings("serial")
None.gif@Entity
None.gif@Table(name = "THEATER")
None.gif@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
ExpandedBlockStart.gifpublic class Theater implements Serializable {
InBlock.gif
InBlock.gif    @ManyToMany(
InBlock.gif            targetEntity=net.allen.domain.Audience.class,
ExpandedSubBlockStart.gif            cascade ={CascadeType.PERSIST,CascadeType.MERGE},
InBlock.gif            fetch=FetchType.LAZY
InBlock.gif    )
InBlock.gif    @JoinTable(
InBlock.gif            name="THEATER_AUDIENCE",
ExpandedSubBlockStart.gif            joinColumns={@JoinColumn(name="THEATER_ID")},
ExpandedSubBlockStart.gif            inverseJoinColumns={@JoinColumn(name="AUDIENCE_ID")}
InBlock.gif    )
InBlock.gif    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
InBlock.gif private List<Audience> audiences = new ArrayList<Audience>();
InBlock.gif
ExpandedSubBlockStart.gif /**
InBlock.gif     * @return Returns the audiences.
ExpandedSubBlockEnd.gif */
ExpandedSubBlockStart.gif public List<Audience> getAudiences() {
InBlock.gif return audiences;
ExpandedSubBlockEnd.gif    }
InBlock.gif
ExpandedSubBlockStart.gif /**
InBlock.gif     * @param audiences The audiences to set.
ExpandedSubBlockEnd.gif */
ExpandedSubBlockStart.gif public void setAudiences(List<Audience> audiences) {
InBlock.gif this.audiences = audiences;
ExpandedSubBlockEnd.gif    }
ExpandedBlockEnd.gif}

功能说明:
@ManyToMany注解
     targetEntity属性:指向被关联端的实体对象
     cascade属性:与Hibernate xml配置文件中的意思一样,这里选用两种方式
            CascadeType.PERSIST:若实体是处于被管理状态,或当persist()方法被调用时,触发级联创建(create)操作。   
            CascadeType.MERGE:若实体是处于被管理状态,或当merge)方法被调用时,触发级联合并(merge)操作。
             其它属性如CascadeType.REMOVE、CascadeType.REFRESH、CascadeType.ALL等属性可参考Hibernate Annotations Reference。
     fetch属性:关联关系获取方式
               LAZY(默认值)在第一次访问关联对象时才触发相应的查询操作。
               另一个值EAGER是通过out join select直接获取关联对象
@JoinTable注解
     name属性:指定关联表名 若不指定Hibernate可以根据既定的规则自动生成(具体规则见reference)
     joinColumns属性:指定主体端的外键
     inverseJoinColumns属性:指定被关联端的外键

@Cache注解
     usage属性:给定了缓存的并发策略
3)找到霸天虎--被关联端:

ExpandedBlockStart.gif/**
InBlock.gif * Audience
InBlock.gif * @author allen
ExpandedBlockEnd.gif */
None.gif
None.gif@SuppressWarnings("serial")
None.gif@Entity
None.gif@Table(name = "AUDIENCE")
None.gif@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
ExpandedBlockStart.gifpublic class Audience implements Serializable {
InBlock.gif
InBlock.gif    @ManyToMany(
ExpandedSubBlockStart.gif           cascade={CascadeType.PERSIST,CascadeType.MERGE},
InBlock.gif           mappedBy="audiences"
InBlock.gif    )
ExpandedSubBlockStart.gif /** 所在的剧院 */
InBlock.gif private List<Theater> theaters = new ArrayList<Theater>();
InBlock.gif
ExpandedSubBlockStart.gif /**
InBlock.gif     * @return Returns the theaters.
ExpandedSubBlockEnd.gif */
ExpandedSubBlockStart.gif public List<Theater> getTheaters() {
InBlock.gif return theaters;
ExpandedSubBlockEnd.gif    }
InBlock.gif
ExpandedSubBlockStart.gif /**
InBlock.gif     * @param theaters The theaters to set.
ExpandedSubBlockEnd.gif */
ExpandedSubBlockStart.gif public void setTheaters(List<Theater> theaters) {
InBlock.gif this.theaters = theaters;
ExpandedSubBlockEnd.gif    }
ExpandedBlockEnd.gif}

功能说明:
@ManyToMany注解
     mappedBy属性:指定了主体端的属性名,用以绑定双方的关系   
汽车人,变形!--如何操作

ExpandedBlockStart.gif/**
InBlock.gif     * select transformers wathers from ShowMax Theater
ExpandedBlockEnd.gif */
ExpandedBlockStart.gif protected void selectWathers() {
InBlock.gif //1) get current theater
InBlock.gif        Theater theater = findTheaterById("showMax");
InBlock.gif //2) clear theater's audiences
InBlock.gif        theater.getAudiences().clear();
InBlock.gif //3) get audiences who want to watch transformers
InBlock.gif        List<Audience> audiences = findAudiencesByMovie("transformers");
ExpandedSubBlockStart.gif for (Audience a: audiences) {
InBlock.gif //4) mountain relations
InBlock.gif            a.getTheaters().add(theater);
InBlock.gif            theater.getAudiences().add(a);
ExpandedSubBlockEnd.gif        }
InBlock.gif //5) do save main entity
InBlock.gif        doSaveEntity(theater);
ExpandedBlockEnd.gif    }

tips:注意第二步的操作。

好了,大功告成!说回电影,红蜘蛛这小子跑得还挺快,期待续集!

转载于:https://my.oschina.net/u/560500/blog/62058

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值