---
title: "初次步入Hibernate Annotation"
author: "east_java"
date: "2008-11-22T16:56:17Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-annotation"
draft: false
lastmod: "2008-11-22T17:05:15Z"
id: 274170
url: "https://japi.iteye.com/blog/274170"
---

Hibernate Annotation早已经出现...
JPA早已被炒得爆了锅...但我才刚刚学习...

最近在重构网站的时候,类的移动免不了.虽然IDE帮了很多的忙,但在XML文件中的类路径不会变化..每次移了类都得再一个一个地找XML文件的类.
使用注解方式也得去修改XML文件,但相对于完全使用XML文件,减少了修改类之间有引用时的修改,只需要修改下总的配置文件就OK了.何乐而不会.

参考文章http://www.blogjava.net/bolo/archive/2008/09/19/229823.html

首先下载必要的包..hibernate hibernate-annotations 
            ejb3-persistence  hibernate-commons-annotations 
下载的时候得<span style="color:red">注意包的兼容性</span>.在hibernate的官网上已经说明了下载注解包时需下载哪个core包..
不然就可能出现类似

```java
tried to access field org.hibernate.cfg.Configuration. xmlHelper from class org.hibernate.cfg.AnnotationConfiguration

```

的错误

还要注意hibernate新版本中的日志记录改为使用slf4j,得把下载包中的lib\required下的jar文件也放到工程中.
不然会出现类似

```java
Failed to load class "org.slf4j.impl.StaticLoggerBinder"
```
错误
别的有使用的包也要重新导入新的版本.比如ehcache,得使用ehcache-1.2.3.jar包..
过去使用的低版本得换掉
不然会出现

```java
java.lang.IllegalAccessError: tried to access method net.sf.ehcache.CacheManager.()V from class org.hibernate.cache.EhCacheProvider 
```


准备工作完成之后,就可以写代码了..
一个POJO.

```java

@Entity   
@Table(name = "teacher_info")//实体类和数据库表名不一致时,才用这个   
public class UserMember implements java.io.Serializable {   
   
    @Id   
    @GeneratedValue(generator = "system-uuid")   
    @GenericGenerator(name = "system-uuid", strategy = "uuid")   
    private String id;   
   
    @Column(updatable = false, nullable = false, length = 20)   
    private String logonName; 
 
```


在导入Entity时,会有两个,一个是persistence包下还有一个是hibernate annotation下,得导入persistence下的.
http://www.hibernate.org/329.html

> I use @org.hibernate.annotations.Entity and get an Unknown entity exception
> Always import @javax.persistence.Entity
> 
> @org.hibernate.annotations.Entity completes @javax.persistence.Entity but is not a replacement
> 


写完后.第三步就是在hibernate.config下配置.

```java
<mapping class="com.james.business.modle.domain.Event" /> 
```

不再是过去的

```java
<mapping resource="com/james/business/modle/domain/Event.hbm.xml" />
```


还有就是

> 用org.hibernate.cfg.AnnotationConfiguration替代以前的org.hibernate.cfg.Configuration，来初始化org.hibernate.SessionFactory。
> 
> 初始化方法，sessionFactory = new AnnotationConfiguration().configure() .buildSessionFactory();
> 
> 如果这时使用sessionFactory = new Configuration().configure() .buildSessionFactory()，会报异常：An AnnotationConfiguration instance is required to use 。
> 


如果是用的spring,并且想映射文件与注解方式一并使用

```java
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.[color=red]LocalSessionFactoryBean[/color]">
<property name="dataSource" ref="dataSource"/>
<property name="configLocations">
<list>
<value>classpath*:/config/hibernate.cfg.xml</value>
</list>
</property>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
```


OK了.annonation的基本上就这些..当然还有关系间的映射之类,但慢慢去了解使用.

在hibernate升级后,得注意下对于select count语句的返回值问题..
过去hibernate3.2都是返回Integer
但现在3.3是返回Long...我在升级包后,重新junit的时候,就出现了classcastexception

> 这个变化主要是为了兼容JPA，可以在hibernate.org的最新文档中找到说明。 
> 
> Hibernate Team也提供了一个与原来兼容的解决方案： 
> 
>   Configuration classicCfg = new Configuration(); 
>   classicCfg.addSqlFunction( "count", new ClassicCountFunction()); 
>   classicCfg.addSqlFunction( "avg", new ClassicAvgFunction()); 
>   classicCfg.addSqlFunction( "sum", new ClassicSumFunction()); 
>   SessionFactory classicSf = classicCfg.buildSessionFactory(); 
> 


也可以使用这种方法

```java
 @Override
  public int countAllSubject() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Number number=((Number) session.createQuery(
        "select count(*) from Post where idParent=0").iterate().next());
    return number.intValue();
        
  }
```


> 因为无论是Long还是Integer,还是BigInteger,它们都是Number的子类,所以用Number去cast这个结果是肯定不会错的,然后,最好定义在Number里面这些方法可以统一的返回需要的类型; 
> 
> byte byteValue() 
>           以 byte 形式返回指定的数值。 
> abstract  double doubleValue() 
>           以 double 形式返回指定的数值。 
> abstract  float floatValue() 
>           以 float 形式返回指定的数值。 
> abstract  int intValue() 
>           以 int 形式返回指定的数值。 
> abstract  long longValue() 
>           以 long 形式返回指定的数值。 
> short shortValue() 
>           以 short 形式返回指定的数值。



以上就是在使用annotation后遇到的一些问题.