`

Hibernate Annotation简单实现

阅读更多
<!--[if !supportLists]-->1.    <!--[endif]-->JDK1.5的Annotation特性

在涉及Hibernate Annotation前,不得不说一下JDK1.5版本提供的Annotation特性,因为他才是Hibernate Annotation的基础。其实说起注解语法,对于任何一个Java开发人员来说都已经耳熟能详了,我们每天都在使用着 @author, @param,等等编写注释,然后用javadoc生成文档。Java的这种方便的文档生成方法受到了开发者的普遍赞誉。JDK默认有3个annotation类型(都在java.lang包下):
(1)@Override:                      该方法是重写方法(只能用在方法上)
(2)@Deprecated:                  不建议使用(过时)的东西
(3)@SuppressWarnings:        暂时把警告信息去掉

前2个没什么好说的,@SuppressWarnings需要一个参数,
如 @SuppressWarnings(value="unchecked") ,"value="可以省略
参数大致有以下这些:
deprecation    使用了过时的类或方法时的警告
unchecked    执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型
fallthrough    当Switch 程序块直接通往下一种情况而没有 Break 时的警告
path              在类路径、源文件路径等中有不存在的路径时的警告
serial            当在可序列化的类上缺少 serialVersionUID 定义时的警告
finally           任何 finally 子句不能正常完成时的警告
all                 关于以上所有情况的警告



<!--[if !supportLists]-->2.    <!--[endif]-->Hibernate的配置策略

Hibernate传统的配置方法是编写hibernate.cfg.xml文件和具体的bean实例的bean.hbm.xml配置文件,并且把该文件在hibernate.cfg.xml文件中作映射来实现的。我们要来维护这两个文件,如果POJO的实体类数量越多,那么我们需要维护的配置文件也就越多。Hibernate Annotation的出现树的我们只维护hibernate.cfg.xml成为可能。在这种新的策略下我们可以利用注释在POJO类中进行属性与数据库表的映射,并且在hibernate.cfg.xml中直接对bean类所在类路径进行映射即可。



<!--[if !supportLists]-->3.    <!--[endif]-->Hibernate Annotation语法

    @Entity                                                     --声明为一个实体bean
    @Table(name="promotion_info")                 --为实体bean映射指定表(表名="promotion_info)
    @Id                                                          --声明了该实体bean的标识属性
    @GeneratedValue                                       --可以定义标识字段的生成策略.
    @Column(name="promotion_remark")         --声明列(字段名="promotion_total") 属性还包括(length=200等)

    @base(fetch=FrtchType.LAZY)                  --延迟获取,在创建实体bean时不会即时将这个属性从数据库中  读出,只有在实体bean这个属性第一次调用时获取相应值。当然默认的fetch属性是时将这个属性从数据库中读出的。



在对一个类进行注解时,可以选择对它的属性或者方法进行注解,根据选择,Hebernate的访问类型分别为field或者property.如果访问类型为property就要在getter()上注解,类型为field就在字段上进行注解声明。



具体应用实例:



package bean;

import javax.persistence.*;



@Entity

@Table(name="customer")

public class Customer {

    @Id        //声明了该实体bean的标识属性

//Hibernate 根据数据库给出一个合适的主键生成策略.

//AUTO--可以是identity类型的字段,或者sequence类型或者table类型,取决于不同的底层数据库

    @GeneratedValue(strategy=GenerationType.AUTO)

          

private int id;

    @Column(name="name")        //将属性映射到列

    private String cName;

   

    @Column(name="age")

    private int age;

   

    @Column(name="email")

    private String email;



    public int getId() {

       return id;

    }



    public void setId(int id) {

       this.id = id;

    }



    public String getName() {

       return cName;

    }



    public void setName(String cName) {

       this.cName = cName;

    }



    public int getAge() {

       return age;

    }



    public void setAge(int age) {

       this.age = age;

    }



    public String getEmail() {

       return email;

    }



    public void setEmail(String email) {

       this.email = email;

    }



}



<!--[if !supportLists]-->4.    <!--[endif]-->数据库表结构



id
name
age
email

1
benson
21
peng@sina.com

2
laura
22
lla@163.com




<!--[if !supportLists]-->5.    <!--[endif]-->hibernate.cfg.xml配置文件

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



<hibernate-configuration>



    <session-factory>

        <property name="connection.username">root</property>

        <property name="connection.url">jdbc:mysql://localhost:3306/book</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="myeclipse.connection.profile">MySql_hibernate</property>

        <property name="connection.password">root</property>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

   

    <!-- 以下设置对象与数据库表格映像类别 -->

        <mapping class="bean.Customer"/>

    </session-factory>



</hibernate-configuration>



注意一下: <mapping class="bean.Customer"/>我们不再使用传统方式在该文件中映射bean.hbm.xml文件,而是直接映射bean的类文件。



<!--[if !supportLists]-->6.<!--[endif]-->JAVA文件

HibernateSessionFactory

package dao;

public class HibernateSessionFactory {

    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

       //这里使用 AnnotationConfiguration 这也是与传统方式的区别         


    private static Configuration configuration = new  AnnotationConfiguration();

    private static org.hibernate.SessionFactory sessionFactory;

    private static String configFile = CONFIG_FILE_LOCATION;



    static {

        try {

            configuration.configure(configFile);

            //configuration.configure();

            sessionFactory = configuration.buildSessionFactory();

        } catch (Exception e) {

            System.err

                    .println("%%%% Error Creating SessionFactory %%%%");

            e.printStackTrace();

        }

    }

    private HibernateSessionFactory() {

    }

    public static synchronized Session getSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

        if (session == null || !session.isOpen()) {

            if (sessionFactory == null) {

                rebuildSessionFactory();

            }

            session = (sessionFactory != null) ? sessionFactory.openSession()

                    : null;

            threadLocal.set(session);

        }

        return session;

    }

    public static void rebuildSessionFactory() {

        try {

            configuration.configure(configFile);

            sessionFactory = configuration.buildSessionFactory();

        } catch (Exception e) {

            System.err

                    .println("%%%% Error Creating SessionFactory %%%%");

            e.printStackTrace();

        }

    }

    public static void closeSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

        threadLocal.set(null);

        if (session != null) {

            session.close();

        }

    }



    public static synchronized  org.hibernate.SessionFactory getSessionFactory() {

        return sessionFactory;

    }



    public static void setConfigFile(String configFile) {

        HibernateSessionFactory.configFile = configFile;

        sessionFactory = null;

    }

    public static Configuration getConfiguration() {

        return configuration;

    }

}

TestAnnotation

package main;



public class TestAnnotation {



    /**

     * @param args

     */

    public static void main(String[] args) {

        // 将持久化的物件

        Customer user = new Customer();

        user.setName("wangpeng55");

        user.setAge(29); 

        user.setEmail("wang55@sohu.cn");



        // 开启Session,相当于开启JDBC的Connection

        Session session = HibernateSessionFactory.getSession();

        // Transaction表示一组会话操作

        Transaction tx= session.beginTransaction();

        // 将对象映像至数据库表格中储存

        session.save(user);

        tx.commit();

        HibernateSessionFactory.closeSession();

        HibernateSessionFactory.getSessionFactory().close();

      

        System.out.println("success!");

    }




本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/pengpeng2395/archive/2008/09/02/2866801.aspx
0
0
分享到:
评论

相关推荐

    hibernate annotation 中文文档

    2.2.2. 映射简单属性 2.2.2.1. 声明基本的属性映射 2.2.2.2. 声明列属性 2.2.2.3. 嵌入式对象(又名组件) 2.2.2.4. 无注解之属性的默认值 2.2.. 映射主键属性 2.2.4. 映射继承关系 2.2.4.1. 每个类一张表 2.2.4.2. 每...

    hibernate annotation帮助文档

    2.2.2. 映射简单属性 2.2.2.1. 声明基本的属性映射 2.2.2.2. 声明列属性 2.2.2.3. 嵌入式对象(又名组件) 2.2.2.4. 无注解之属性的默认值 2.2.. 映射主键属性 2.2.4. 映射继承关系 2.2.4.1. 每个类一张表 2.2....

    Hibernate_Annotation关联映射

    Hibernate Annotation几种关联映射 一对一(One-To-One) ...以上是整理的一点简单的几种映射,可参考EJB3.pdf中P111——P131,hibernate_annotation.pdf 第二章 在这里没有具体的例子,有很多内容还需要仔细查看文档。

    springMVC + spring + hibernate 整合的管理系统小案例

    下载后请修改数据库用户名和密码,即springAnnotation-hibernate.xml文件 案例系统支持功能如下: 注册功能,身份证,邮箱,手机号,姓名等校验,ajax异步获取资源 分页显示,编辑更新,多行删除等更功能,使用了MVC...

    Hibernate+中文文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    hibernate3.2中文文档(chm格式)

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    HibernateAPI中文版.chm

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    "以物换物"平台源代码(ssh实现)

    学校软件工程的一个课程设计,通过struts2、hibernate、spring实现,其中设计struts标签库和spring、hibernate的annotation。实现个功能比较简单易懂。资源为“以物换物”平台,有登录、注册、发起物品、回复、提出...

    Hibernate 中文 html 帮助文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) ...

    Hibernate中文详细学习文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    最全Hibernate 参考文档

    4.1. 一个简单的POJO例子 4.1.1. 为持久化字段声明访问器(accessors)和是否可变的标志(mutators) 4.1.2. 实现一个默认的(即无参数的)构造方法(constructor) 4.1.3. 提供一个标识属性(identifier property)(可...

    自定义Orm框架的实现

    该项目是一个Hibernate框架的简单实现,里面通过Jdk5.0的Annotation实现从对象到数据库之间的映射, 功能类似于小型的Hibernate框架

    hibernate 体系结构与配置 参考文档(html)

    使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) ...

    Hibernate教程

    6.4.2. 使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. ...

    Hibernate注释大全收藏

    Hibernate 使用 SQL Union 查询来实现这种策略。 这种策略支持双向的一对多关联,但不支持 IDENTIFY 生成器策略,因为ID必须在多个表间共享。一旦使用就不能使用AUTO和IDENTIFY生成器。 每个类层次结构一张表 @...

    Hibernate_3.2.0_符合Java习惯的关系数据库持久化

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    Struts2.5.10+Spring4.3.4+Hibernate5.2.4整合所需要的jar包

    Struts2.5.10+Spring4.3.4+Hibernate5.2.4整合所需要的jar包,包括xml配置方式和annotation配置方式所需要的jar包,本人已确认过,搭建起来实现简单的增删改查没有问题。本人也在学习阶段,若有问题请留言,互相学习...

    Hibernate3的帮助文档

    6.4.2. 使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. ...

    hibernate3.04中文文档.chm

    6.4.2. 使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. ...

    Hibernate3+中文参考文档

    4.1. 一个简单的POJO例子 4.1.1. 为持久化字段声明访问器(accessors)和是否可变的标志(mutators) 4.1.2. 实现一个默认的(即无参数的)构造方法(constructor) 4.1.3. 提供一个标识属性(identifier property)(可...

Global site tag (gtag.js) - Google Analytics