Hibernate Annotation文档整理(一)

Setting up an annotations project

  • HibernateUtil类(Annotation方式)
public class HibernateUtil {
private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new AnnotationConfiguration()
                    .configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log exception!
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static Session getSession()
            throws HibernateException {
        return sessionFactory.openSession();
    }
}
 
  • 需要添加hibernate.cfg.xml配置文件,内容如:

     

    <!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
      <session-factory>
        <mapping package="test.animals"/>
        <mapping class="test.Flight"/>
        <mapping class="test.Sky"/>
        <mapping class="test.Person"/>
        <mapping class="test.animals.Dog"/>
    
        <mapping resource="test/animals/orm.xml"/>
      </session-factory>
    </hibernate-configuration>
     


    hibernate 特定的属性



Property  描述 
hibernate.cache.default_cache_concurrency_strategy
当使用注解@Cacheable @Cache时,用来给的默认org.hibernate.annotations.CacheConcurrencyStrategy设置名称,@Cache(strategy="..") 可以覆盖默认设置。 
hibernate.id.new_generator_mappings 
值为true或者false,这个设置表示是否新建的IdentifierGenerator实现类的生成策略为AUTO、Table和Sequence。默认为false,以保持向后兼容性。

我们建议所有新项目使用hibernate.id.new_generator_mappings= true,新的生成器是更有效率和更密切的JPA规范语义。然而,他们不向后兼容现有的数据库(如果ID生成一个序列或表)。

Mapping Entities

Marking a POJO as persistent entity

@Entity
public class Flight implements Serializable {
    Long id;

    @Id
    public Long getId() { return id; }

    public void setId(Long id) { this.id = id; }
}
public class Flight implements Serializable {
 

Defining the table

@Table元素包含一个schema和catalog属性,如果他们需要被定义。

你还可以使用@ UniqueConstraint 给表定义唯一约束(建议使用@Column.unique方法。)

 

@Table(name="tbl_sky",
    uniqueConstraints = {@UniqueConstraint(columnNames={"month", "day"})}
)
 

通过@Version设置乐观锁

@Entity
public class Flight implements Serializable {
    ...
    @Version
    @Column(name="OPTLOCK")
    public Integer getVersion() { ... }
}
 

version这个属性会被映射成为乐观锁字段,实体管理器会通过它检测到有冲突的更新。为了防止丢失更新,可以设置最晚提交生效策略(last-commit-wins strategy)。

version字段可以是数字或者时间戳,Hibernate支持自定义的或者适当的实现UserVersionType的类型。

Mapping simple properties

Declaring basic property mappings(声明基本属性映射)

实体中任何一个非静态的、非暂时性属性都认为是持久化字段,除非使用@Transient注解。

属性不加注解相当于加@Basic,@Basic允许声明加载策略(FetchType)。

 

public transient int counter; //transient property

private String firstname; //persistent property

@Transient
String getLengthInMeter() { ... } //transient property

String getName() {... } // persistent property

@Basic
int getLength() { ... } // persistent property

@Basic(fetch = FetchType.LAZY)
String getDetailedComment() { ... } // persistent property

@Temporal(TemporalType.TIME)
java.util.Date getDepartureTime() { ... } // persistent property

@Enumerated(EnumType.STRING)
Starred getNote() { ... } //enum persisted as String in database
 

在普通的Java API中,时间精度是没有定义的。当处理时间数据时,你可能需要在数据库中描述期望的时间精度。

时间数据可以有DATE、TIME、TIMESTAMP的精度,通过@Temporal注解可以微调。

@Lob标识属性应该持久化为Blob或者Clob类型,这决定于属性的类型。
java.sql.Clob、Character[]、char[] 和 String会持久化成Clob。
java.sql.Blob、Byte[]、byte[]和Serializable会被持久化成Blob。

 

@Lob
public String getFullText() {
    return fullText;
}

@Lob
public byte[] getFullCode() {
    return fullCode;
}
 

猜你喜欢

转载自neo19860208.iteye.com/blog/1457190