`
baoguohang
  • 浏览: 3311 次
  • 性别: Icon_minigender_1
  • 来自: 哈尔滨
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Hibernate Annotation

阅读更多
继承策略:Single table per class hierarchy strategy
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="planetype",
    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue("Plane")
public class Plane { ... }

@Entity
@DiscriminatorValue("A320")
public class A320 extends Plane { ... }


table-per-subclass:
@Entity @Table(name="CATS")
@Inheritance(strategy=InheritanceType.JOINED)
public class Cat implements Serializable { 
    @Id @GeneratedValue(generator="cat-uuid") 
    @GenericGenerator(name="cat-uuid", strategy="uuid")
    String getId() { return id; }

    ...
}

@Entity @Table(name="DOMESTIC_CATS")
@PrimaryKeyJoinColumn(name="CAT")
public class DomesticCat extends Cat { 
    public String getName() { return name; }
}


Table per class strategy:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Flight implements Serializable { ... }    


Inherit properties from superclasses:

//某些表有共同属性但不必把超类持久化
@MappedSuperclass
public class BaseEntity {
    @Basic
    @Temporal(TemporalType.TIMESTAMP)
    public Date getLastUpdate() { ... }
    public String getLastUpdater() { ... }
    ...
}

@Entity class Order extends BaseEntity {
    @Id public Integer getId() { ... }
    ...
}


覆盖超类的字段:
@MappedSuperclass
public class FlyingObject implements Serializable {

    public int getAltitude() {
        return altitude;
    }

    @Transient
    public int getMetricAltitude() {
        return metricAltitude;
    }

    @ManyToOne
    public PropulsionType getPropulsion() {
        return metricAltitude;
    }
    ...
}

@Entity
@AttributeOverride( name="altitude", column = @Column(name="fld_altitude") )
@AssociationOverride( 
   name="propulsion", 
   joinColumns = @JoinColumn(name="fld_propulsion_fk") 
)
public class Plane extends FlyingObject {
    ...
}


Mapping one to one and one to many associations:
cascade属性:级联操作
By default, single point associations are eagerly fetched in JPA 2. You can mark it as lazily fetched by using @ManyToOne(fetch=FetchType.LAZY) in which case Hibernate will proxy the association and load it when the state of the associated entity is reached.:单端关联使用Annotation lazy默认为false

Using a foreign key or an association table:

@Entity
public class Flight implements Serializable {
    @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
    @JoinColumn(name="COMP_ID")
    public Company getCompany() {
        return company;
    }
    ...
}          

The @JoinColumn attribute is optional:上例默认为company_id

You can also map a to one association through an association table:关联表关联
@Entity
public class Flight implements Serializable {
    @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
    @JoinTable(name="Flight_Company",
        joinColumns = @JoinColumn(name="FLIGHT_ID"),
        inverseJoinColumns = @JoinColumn(name="COMP_ID")
    )
    public Company getCompany() {
        return company;
    }
    ...
}       


关联对象找不到时的处理:

@Entity
public class Child {
    ...
    @ManyToOne
    @NotFound(action=NotFoundAction.IGNORE)
    public Parent getParent() { ... }
    ...
}


改变外键名称:
@Entity
public class Child {
    ...
    @ManyToOne
    @ForeignKey(name="FK_PARENT")
    public Parent getParent() { ... }
    ...
}


关联非主键以外的属性:
@Entity
class Person {
   @Id Integer personNumber;
   String firstName;
   @Column(name="I")
   String initial;
   String lastName;
}

@Entity
class Home {
   @ManyToOne
   @JoinColumns({
      @JoinColumn(name="first_name", referencedColumnName="firstName"),
      @JoinColumn(name="init", referencedColumnName="I"),
      @JoinColumn(name="last_name", referencedColumnName="lastName"),
   })
   Person owner
}


拥有相同主键:
@Entity
public class Body {
    @Id
    public Long getId() { return id; }

    @OneToOne(cascade = CascadeType.ALL)
    @MapsId
    public Heart getHeart() {
        return heart;
    }
    ...
}   

@Entity
public class Heart {
    @Id
    public Long getId() { ...}
}     


How to map collections:
@Entity
public class Product {

    private String serialNumber;
    private Set<Part> parts = new HashSet<Part>();

    @Id
    public String getSerialNumber() { return serialNumber; }
    void setSerialNumber(String sn) { serialNumber = sn; }
   
    @OneToMany
    @JoinColumn(name="PART_ID")
    public Set<Part> getParts() { return parts; }
    void setParts(Set parts) { this.parts = parts; }
}


@Entity
public class Part {
   ...
}


Collection mapping using @OneToMany and @JoinTable:关联表方式

@Entity
public class Product {

    private String serialNumber;
    private Set<Part> parts = new HashSet<Part>();

    @Id
    public String getSerialNumber() { return serialNumber; }
    void setSerialNumber(String sn) { serialNumber = sn; }
   
    @OneToMany
    @JoinTable(
            name="PRODUCT_PARTS",
            joinColumns = @JoinColumn( name="PRODUCT_ID"),
            inverseJoinColumns = @JoinColumn( name="PART_ID")
    )
    public Set<Part> getParts() { return parts; }
    void setParts(Set parts) { this.parts = parts; }
}


@Entity
public class Part {
   ...
}


对于单向一对多关联:外键默认为空,可能需要设置@JoinColumn(nullable=false)

排序的List
@Entity
public class Customer {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;

   @OneToMany(mappedBy="customer")
   @OrderBy("number")
   public List<Order> getOrders() { return orders; }
   public void setOrders(List<Order> orders) { this.orders = orders; }
   private List<Order> orders;
}

@Entity
public class Order {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;

   public String getNumber() { return number; }
   public void setNumber(String number) { this.number = number; }
   private String number;

   @ManyToOne
   public Customer getCustomer() { return customer; }
   public void setCustomer(Customer customer) { this.customer = customer; }
   private Customer number;
}

-- Table schema
|-------------| |----------|
| Order       | | Customer |
|-------------| |----------|
| id          | | id       |
| number      | |----------|
| customer_id |
|-------------|

存储集合的Key:

@Entity
public class Customer {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;

   @OneToMany(mappedBy="customer")
   @OrderColumn(name="orders_index")
   public List<Order> getOrders() { return orders; }
   public void setOrders(List<Order> orders) { this.orders = orders; }
   private List<Order> orders;
}

@Entity
public class Order {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;

   public String getNumber() { return number; }
   public void setNumber(String number) { this.number = number; }
   private String number;

   @ManyToOne
   public Customer getCustomer() { return customer; }
   public void setCustomer(Customer customer) { this.customer = customer; }
   private Customer number;
}


此处的mappedBy相当于inverse,只出现在双向关联中,mappedBy的另一方为外键的持有方,只要另一方维护了关联,就不需要双方的维护了了

Maps:
@Entity
public class Customer {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;

   @OneToMany(mappedBy="customer")
   @MapKey(name="number")
   public Map<String,Order> getOrders() { return orders; }
   public void setOrders(Map<String,Order> order) { this.orders = orders; }
   private Map<String,Order> orders;
}

@Entity
public class Order {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;

   public String getNumber() { return number; }
   public void setNumber(String number) { this.number = number; }
   private String number;

   @ManyToOne
   public Customer getCustomer() { return customer; }
   public void setCustomer(Customer customer) { this.customer = customer; }
   private Customer number;
}

-- Table schema
|-------------| |----------|
| Order       | | Customer |
|-------------| |----------|
| id          | | id       |
| number      | |----------|
| customer_id |
|-------------|

双向关联
@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
}   


Many to many association via @ManyToMany
@Entity
public class Employer implements Serializable {
    @ManyToMany(
        targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,
        cascade={CascadeType.PERSIST, CascadeType.MERGE}
    )
    @JoinTable(
        name="EMPLOYER_EMPLOYEE",
        joinColumns=@JoinColumn(name="EMPER_ID"),
        inverseJoinColumns=@JoinColumn(name="EMPEE_ID")
    )
    public Collection getEmployees() {
        return employees;
    }
    ...
}              

@Entity
public class Employee implements Serializable {
    @ManyToMany(
        cascade = {CascadeType.PERSIST, CascadeType.MERGE},
        mappedBy = "employees",
        targetEntity = Employer.class
    )
    public Collection getEmployers() {
        return employers;
    }
}           

<class name="Parent">
    <id name="id" column="parent_id"/>
    ....
    <map name="children" inverse="true">
        <key column="parent_id"/>
        <map-key column="name" 
            type="string"/>
        <one-to-many class="Child"/>
    </map>
</class>

<class name="Child">
    <id name="id" column="child_id"/>
    ....
    <property name="name" 
        not-null="true"/>
    <many-to-one name="parent" 
        class="Parent" 
        column="parent_id"
        not-null="true"/>
</class>

上面的map-key有对应的列
<class name="Parent">
    <id name="id" column="parent_id"/>
    ....
    <map name="children">
        <key column="parent_id"
            not-null="true"/>
        <map-key column="name" 
            type="string"/>
        <one-to-many class="Child"/>
    </map>
</class>

<class name="Child">
    <id name="id" column="child_id"/>
    ....
    <many-to-one name="parent" 
        class="Parent" 
        column="parent_id"
        insert="false"
        update="false"
        not-null="true"/>
</class>

没有对应列的时候,不能使用inverse=true,参上面代码

public class Parent {
    @Id
    @GeneratedValue
    private long id;

    @OneToMany([color=red]optional=false[/color])
    private Set<Child> children;

    // getter/setter
    ...
}


public class Child {
   @Id
   @GeneratedValue
   private long id;
   private String name;

   
   // getter/setter
   ...
}

optional=false相当于外键不能为空


    persist() 使一个临时实例持久化。然而,它不保证立即把标识符值分配给持久性实例,这会发生在冲刷(flush)的时候。persist() 也保证它在事务边界外调用时不会执行 INSERT 语句。这对于长期运行的带有扩展会话/持久化上下文的会话是很有用的。

    save() 保证返回一个标识符。如果需要运行 INSERT 来获取标识符(如 "identity" 而非 "sequence" 生成器),这个 INSERT 将立即执行,不管你是否在事务内部还是外部。这对于长期运行的带有扩展会话/持久化上下文的会话来说会出现问题。
分享到:
评论

相关推荐

    Hibernate Annotation jar

    这里面包涵了需要用Hibernate Annotation时,所需要的所有jar包! 现在我们公司在做web项目的时候,已经不用*.hbm.xml这种映射文件了,都是用Annotation(注解)方式来完成实体与表之间的映射关系,这样看起来比用...

    hibernate annotation中文文档

    hibernate annotation中文文档

    hibernate annotation 中文文档

    《Hibernate Annotation 中文文档》是Java开发者们的重要参考资料,它详细介绍了如何在Hibernate框架中使用注解进行对象关系映射(ORM)。Hibernate是一款强大的开源Java持久化框架,它简化了数据库与Java对象之间的...

    Hibernate Annotation库

    Hibernate Annotation库是Java开发中用于简化对象关系映射(ORM)的一个重要组件,它使得开发者能够在Java类上直接使用注解来定义数据库映射,从而避免了传统的XML配置文件。这三个特定的jar包是Hibernate ORM框架中...

    最全的Hibernate Annotation API文档

    在Hibernate中,注解(Annotation)是一种声明式的方法,用于配置实体类、属性以及它们与数据库表之间的映射关系。本文将深入探讨“最全的Hibernate Annotation API文档”中的关键知识点。 一、实体类(Entity) 在...

    Hibernate Annotation入门

    **Hibernate Annotation 入门** Hibernate 是一款非常流行的Java对象关系映射(ORM)框架,它允许开发者使用面向对象的方式操作数据库。而Hibernate Annotation是Hibernate的一个重要特性,它通过在Java类和字段上...

    hibernate annotation hibernate3

    《Hibernate注解与Hibernate3深度解析》 在Java开发领域,Hibernate作为一种强大的对象关系映射(ORM)框架,极大地简化了数据库操作。本篇将深入探讨Hibernate 3版本中的注解使用,帮助开发者理解如何利用注解进行...

    HibernateAnnotation

    ### HibernateAnnotation 技术概述 在Java开发领域中,Hibernate框架是进行对象关系映射(Object-Relational Mapping,简称ORM)的一种非常流行的工具。它能够帮助开发者将面向对象的模型与关系型数据库进行桥接,...

    sping hibernate Annotation(注释配置) demo(例子)

    总结来说,这个 "Spring Hibernate Annotation demo" 展示了如何在 Spring 框架中使用注解配置来管理依赖,以及如何利用 Hibernate 的注解进行数据持久化。同时,它还涉及到了 Flex 前端与后端的交互。通过学习这个 ...

    Hibernate Annotation 中文文档

    **Hibernate Annotation 中文文档** 在Java的持久化框架中,Hibernate是一个非常重要的工具,它极大地简化了数据库操作。随着技术的发展,Hibernate Annotation逐渐成为主流,因为它提供了更直观、更简洁的方式来...

    Hibernate Annotation 学习笔记

    《Hibernate Annotation 学习笔记》 在Java的持久化框架中,Hibernate以其强大的功能和易用性成为开发者首选之一。而Hibernate Annotation则是Hibernate提供的一种基于注解的实体映射方式,它极大地简化了传统XML...

    Hibernate Annotation 笔记 总结 注解

    【标题】:深入理解Hibernate Annotation及其使用 【描述】:本文将全面介绍Hibernate Annotation的使用,包括事务管理和声明式事务处理,以及如何通过注解简化数据库持久化操作。 【标签】:Hibernate, ...

    hibernate annotation api chm文件

    《Hibernate Annotation API详解》 Hibernate是一个流行的Java持久化框架,它简化了数据库操作,使得开发者可以更专注于业务逻辑而不是底层的数据访问细节。在Hibernate 3.3版本中,引入了Annotation API,这是一种...

    hibernate annotation学习文档

    ### Hibernate Annotation 学习知识点详解 #### 一、概述 Hibernate 是一款开源的对象关系映射 (ORM) 巨具,它极大地简化了 Java 应用程序与数据库之间的交互过程。Hibernate 支持多种注解(Annotation),使得...

    Hibernate Annotation 唯一外键一对一双向关联

    通过阅读《Hibernate_annotation_1to1_foreignKey》文档或博客,你可以更详细地了解如何配置和使用这种关联,包括示例代码、注意事项以及可能遇到的问题和解决方案。理解并熟练运用这些知识,能帮助你在使用...

    Hibernate中文文档+hibernate annotation +distribution

    本文将深入探讨Hibernate的核心概念,结合提供的中文文档,以及hibernate-annotation-3.4.0GA和hibernate-distribution-3.3.2.GA的相关资料,为开发者提供详尽的学习资源。 首先,Hibernate中文文档是理解框架基础...

    HibernateAnnotation3.4.0API

    HibernateAnnotation3.4.0API 该文档根据源码生成为英文文档

    Hibernate Annotation Reference .htm

    Hibernate Annotation Reference .htm

Global site tag (gtag.js) - Google Analytics