Hibernate Annotation简单实现

本文深入探讨了JDK1.5版本提供的Annotation特性的基础及其在Hibernate框架中的应用,通过示例展示了如何使用Annotation进行实体类与数据库表的映射,以及与传统配置方式的区别。重点介绍了如何在POJO类中使用注解进行属性与数据库表的映射,以及在hibernate.cfg.xml文件中的简化配置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!--[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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值