小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Hibernate的Discriminator應(yīng)用

 昵稱14793 2007-02-28
        可能經(jīng)常遇到這樣的情況:
       在數(shù)據(jù)庫表中會有這樣的一個字段用來區(qū)別記錄的屬性,如:在客戶表中有一個字段表示客戶級別,當(dāng)這個記錄為A時是一級客戶,為B時是二級客戶。在用hiberante做OR表示時類可能是這樣的:
       public class Customer{
          private String flag;   //表示客戶的級別
          ...
       }   
       然后,在程序中手動控制flag的值,但是這樣當(dāng)每個級的客戶有不同的屬性時Customer類將包含所有級別的屬性,這樣不是很好。
       hibernate提供一個Discriminator映射的方法,就是把一個表映射成不同的類,有不同的屬性。

       public class Customer{
          //包含所有級別的公共屬性
          ...
        }
      
       public class CustomerA extends Customer{
       //只包括一級客戶的特有屬性
        }

       public class CustomerB extends Customer{
       //只包含二級客戶特有的屬性
        }
這樣更符合面向?qū)ο蟮脑瓌t,然后在hbm.xml中這樣寫:
<id name="id" type="int">
    ...
</id>
<discriminator column="flag" type="string" />
<!-- 公共屬性的映射 -->
<subclass name="CustomerA" discriminator-value="A">
<!-- 一級客戶特有屬性的映射 -->
</subclass>
<subclass name="CustomerB" discriminator-value="B">
<!-- 二級客戶特有屬性的映射 -->
</subclass>

這樣就可以單獨(dú)的用CustomerA,CustomerB這樣的實(shí)例了,做數(shù)據(jù)庫修改時就不用關(guān)心flag字段的值了,會自動的加A或B。

如果是使用hibernate Annotation而不是xml來描述映謝關(guān)系,代碼如下:
@Entity
@Table(name = "customer")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "flag", discriminatorType = DiscriminatorType.STRING)
public class Customer{
}

@Entity
@DiscriminatorValue(value = "A")
public class CustomerA extends Customer{
}

@Entity
@DiscriminatorValue(value = "B")
public class CustomerB extends Customer{
}

這樣就可以了。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多