Hibernate Annotations(一)

Entity注释

@Entity
@BatchSize(size = 5)   //批处理
@Where(clause = "1=1")  //默认查询条件
@FilterDef(name = "minLength", parameters = ...{@ParamDef(name = "minLength", type = "integer")})  //过滤器
@Filters(...{
@Filter(name = "betweenLength"),
@Filter(name = "minLength", condition = ":minLength <= length")
        })
@org.hibernate.annotations.Table(appliesTo = "Forest",
        indexes = ...{@Index(name = "idx", columnNames = ...{"name", "length"})})  //建立索引
@Proxy(lazy = false)  //延迟加载
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)  //cache
public class ...
 

 

过滤器注释的使用

 

s.enableFilter( "betweenLength" ).setParameter( "minLength", 5 ).setParameter( "maxLength", 50 );
count = ( (Long) s.createQuery( "select count(*) from Forest" ).iterate().next() ).intValue();
assertEquals( 1, count );
s.disableFilter( "betweenLength" );
s.enableFilter( "minLength" ).setParameter( "minLength", 5 );
count = ( (Long) s.createQuery( "select count(*) from Forest" ).iterate().next() ).longValue();
assertEquals( 2l, count );
s.disableFilter( "minLength" );
Entity注释主要是添加在class的上面

 

Type注释
 

 

    @Type(type = "text") 
    public String getLongDescription() ...{
        return longDescription;
    }
    @Type(type = "caster")  //取值时转为小写
    public String getSmallText() ...{
        return smallText;
    }

    @Type(type = "caster", parameters = ...{@Parameter(name = "cast", value = "upper")})  //取值时转为大写
    public String getBigText() ...{
        return bigText;
    }
    @Lob  //二进制字段
    public Country getCountry() ...{
        return country;
    }
                     @Formula("maxAltitude * 1000")  //公式(数据库中并不存在这个字段)
    public long getMaxAltitudeInMilimeter() ...{
        return maxAltitudeInMilimeter;
    }
                     @Type(type = "org.hibernate.test.annotations.entity.MonetaryAmountUserType")  //CompositeType
    @Columns(columns = ...{
    @Column(name = "r_amount"),  //数据库字段
    @Column(name = "r_currency")  //数据库字段
                      })
CompositeType实现类

 

 

//$Id: MonetaryAmountUserType.java 11282 2007-03-14 22:05:59Z epbernard $
package org.hibernate.test.annotations.entity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Currency;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;

/** *//**
 * @author Emmanuel Bernard
 */
public class MonetaryAmountUserType implements CompositeUserType ...{

    public String[] getPropertyNames() ...{
        return new String[]...{"amount", "currency"};
    }

    public Type[] getPropertyTypes() ...{
        return new Type[]...{Hibernate.BIG_DECIMAL, Hibernate.CURRENCY};
    }

    public Object getPropertyValue(Object component, int property) throws HibernateException ...{
        MonetaryAmount ma = (MonetaryAmount) component;
        return property == 0 ? (Object) ma.getAmount() : (Object) ma.getCurrency();
    }

    public void setPropertyValue(Object component, int property, Object value)
            throws HibernateException ...{
        MonetaryAmount ma = (MonetaryAmount) component;
        if ( property == 0 ) ...{
            ma.setAmount( (BigDecimal) value );
        }
        else ...{
            ma.setCurrency( (Currency) value );
        }
    }

    public Class returnedClass() ...{
        return MonetaryAmount.class;
    }

    public boolean equals(Object x, Object y) throws HibernateException ...{
        if ( x == y ) return true;
        if ( x == null || y == null ) return false;
        MonetaryAmount mx = (MonetaryAmount) x;
        MonetaryAmount my = (MonetaryAmount) y;
        return mx.getAmount().equals( my.getAmount() ) &&
                mx.getCurrency().equals( my.getCurrency() );
    }

    public int hashCode(Object x) throws HibernateException ...{
        return ( (MonetaryAmount) x ).getAmount().hashCode();
    }

    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
            throws HibernateException, SQLException ...{
        BigDecimal amt = (BigDecimal) Hibernate.BIG_DECIMAL.nullSafeGet( rs, names[0] );
        Currency cur = (Currency) Hibernate.CURRENCY.nullSafeGet( rs, names[1] );
        if ( amt == null ) return null;
        return new MonetaryAmount( amt, cur );
    }

    public void nullSafeSet(
            PreparedStatement st, Object value, int index,
            SessionImplementor session
    ) throws HibernateException, SQLException ...{
        MonetaryAmount ma = (MonetaryAmount) value;
        BigDecimal amt = ma == null ? null : ma.getAmount();
        Currency cur = ma == null ? null : ma.getCurrency();
        Hibernate.BIG_DECIMAL.nullSafeSet( st, amt, index );
        Hibernate.CURRENCY.nullSafeSet( st, cur, index + 1 );
    }

    public Object deepCopy(Object value) throws HibernateException ...{
        MonetaryAmount ma = (MonetaryAmount) value;
        return new MonetaryAmount( ma.getAmount(), ma.getCurrency() );
    }

    public boolean isMutable() ...{
        return true;
    }

    public Serializable disassemble(Object value, SessionImplementor session)
            throws HibernateException ...{
        return (Serializable) deepCopy( value );
    }

    public Object assemble(Serializable cached, SessionImplementor session, Object owner)
            throws HibernateException ...{
        return deepCopy( cached );
    }

    public Object replace(Object original, Object target, SessionImplementor session, Object owner)
            throws HibernateException ...{
        return deepCopy( original ); //TODO: improve
    }

}

 

时间: 2024-09-21 15:10:31

Hibernate Annotations(一)的相关文章

使用Hibernate Annotations维护多对多关系的心得

说明 在HibernateAnnotations中通过@ManyToMany注解可定义多对多关联.同时,也需要通过注解@JoinTable描述关联表和关联条件.对于双向关联,其中一端必须定义为owner,另一端必须定义为inverse(在对关联表进行更性操作时这一端将被忽略).被关联端不必也不能描述物理映射,只需要一个简单的mappedBy参数,该参数包含了主体端的属性名,这样就绑定了双方的关系. 如何制作PO 1)找到CUBE--需要引入哪些类: import java.util.ArrayL

Hibernate Annotations实战(二)

我在前面一篇文章<Hibernate Annotations 实战-- 从 hbm.xml 到 Annotations>中,有很多开发者在谈论中提到,有没有必要从 hbm.xml 往 Annotations 上转移. 那么在这篇文章中我们就来讨论一下 hbm.xml 与 Annotations的优缺点,看看那种情况最适合你. 首先,讨论一下 xml 配置文件的优点, 个人认为主要优点就是当你改变底层配置时 不需要改变和重新编译代码,只需要在xml 中更改就可以了,例如 Hibernate.cf

java.lang.ClassNotFoundException: org.hibernate.annotations.Entity

问题描述 最近要把hibernate从3.2升级到3.67.更换JAR包之后,报以下错误,但那个entity在hibernate3.jar包里面是有.先谢谢大家!gframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282)atorg.springframework.web.context.ContextLoader.initWebApplicationContext(Context

Hibernate Annotations(四)

普通一对多(延迟加载方式)  @OneToMany(mappedBy = "troop", cascade = ...{CascadeType.ALL}, fetch = FetchType.LAZY)     @OrderBy(clause = "name desc")     public Set<Soldier> getSoldiers() ...{         return soldiers;     }     @ManyToOne(fet

Hibernate Annotations实战--从hbm.xml到Annotations

从 hbm.xml 到 Annotations 下面让我们先看一个通常用 hbm.xml 映射文件的例子. 有3个类 .HibernateUtil.java 也就是 Hibernate文档中推荐的工具类,Person.java, Test.java 测试用的类.都在test.hibernate 包中. 每个类的代码如下: HibernateUtil: 01 package test.hibernate; 02 03 import org.hibernate.HibernateException;

Hibernate Annotations(二)

复合主键的应用 (EmbeddedId) 主表 @Entity public class A implements Serializable...{     @EmbeddedId     private AId aId;     public AId getAId() ...{         return aId;     }     public void setAId(AId aId) ...{         this.aId = aId;     } } 复合主键   @Embedd

Hibernate Annotation使用经验总结

在向大家详细介绍使用Hibernate Annotation之前,首先让大家了解下Hibernate的配置依赖于外部 XML 文件,然后全面介绍使用Hibernate Annotation. 在过去几年里,Hibernate不断发展,几乎成为Java数据库持久性的事实标准.它非常强大.灵活,而且具备了优异的性能.在本文中,我们将了解如何使用Java 5 注释来简化Hibernate代码,并使持久层的编码过程变得更为轻松. 传统上,Hibernate的配置依赖于外部 XML 文件:数据库映射被定义

hibernate 多对多 jpa-Hibernate JPA 配置多对多问题

问题描述 Hibernate JPA 配置多对多问题 SysUser.java @ManyToMany(fetch = FetchType.EAGER, targetEntity = SysRole.class) @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @JoinTable(name = "SYS_USER_ROLE", joinColumns={ @JoinColumn(name="USER

Hibernate(5)—— 联合主键 、一对一关联关系映射(xml和注解) 和 领域驱动设计

俗话说,自己写的代码,6个月后也是别人的代码--复习!复习!复习!涉及的知识点总结如下: One to One 映射关系 一对一单向外键(XML/Annotation) 一对一双向外键关联(XML/Annotation) 联合主键 一对一单向外键联合主键(Xml/Annotation) 一对一组件关联(XML/Annotation) 理解组件 领域驱动设计--自动生成数据库脚本 一对一关系的小结 一些出错问题的总结   自动生成数据库脚本 一般在项目开发过程中,我们的习惯是先建好数据库和表,然后