随笔 - 0, 文章 - 75, 评论 - 0, 引用 - 0
数据加载中……

Annotation版本的HelloWorld

在Hibernate3.0以后,开始支持Annotation


Annotation的标准是,建立一个符合JTA标准的Annotation


下载hibernate-annotations-3.4.0.GA工具包后


项目添加:


hibernate-annotations.jar --最核心


lib/ejb3-persistence.jar --符合了JTA标准的Annotation


lib/hibernate-comments-annotations.jar --进行反射时的Annotation



@Entity表示实体类


@Id 标识主键


注意是javax.persistence.*; 下



首先创建DB表:Teacher


id  number


name  varchar2(20)


title  varchar2(20)



编写Teacher类:


Annotation版本的HelloWorld


//省略更多的getter/setter方法



注意,@Id写在getId()方法前,防止属性id名字与getId方法的名字不匹配。如id 和getTeacherId()方法



配置hibernate.cfg.xml文件:


Annotation版本的HelloWorld


注意这里的<mapping class="类名全路径" />



最后测试:


public static void main(String[] args) {
Teacher t = new
Teacher();
t.setId(1);
t.setName("王五");
t.setTitle("中级");
Configuration
conf = new AnnotationConfiguration();
//注意这里使用的是AnnotationConfiguration
conf.configure();
SessionFactory
factory = conf.buildSessionFactory();
Session session =
factory.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
factory.close();
}



只有new AnnotationConfiguration()不一样,其余操作都一样


用Annotation配置javaBean可省略Teacher.hbm.xml的映射文件,操作也方便,你认为呢?



最后:Hibernate-Annotation文档中的小错误:


没有加入hibernate-commen-annotations.jar包



MyEclipse 输入 @ 不给提示时:


window、references、搜content assist、在 activation for java 栏加入"@"


也可以控制delay属性,延迟修改为100则提示很快



解决问题时间:


问题类型:


java.lang.IllegalAccessError: tried to access field
org.slf4j.impl.StaticLoggerBinder.SINGLETON from class
org.slf4j.LoggerFactory

需下载slf4j.jar包


加载\slf4j-1.6.4\integration\lib 下的
slf4j-api-2.0.99.jar和slf4j-nop-1.5.6.jar

refresh,clear,run


Exception in thread "main"
org.hibernate.exception.ConstraintViolationException: Could not execute
JDBC batch update
Caused by: java.sql.BatchUpdateException: ORA-00001: unique
constraint (HT.TEACHER_PK_ID) violated


重复执行时,注意DB主键不能重复

posted on 2012-04-22 15:58 hantai 阅读(169) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: