您的位置:首页 > 其它

Hibernate Annotation简单实现

2008-09-02 14:54 253 查看
1.
[/b]JDK1.5[/b]的[/b]Annotation[/b]特性[/b][/b]

在涉及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 关于以上所有情况的警告

2.
[/b]Hibernate[/b]的配置策略[/b][/b]

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

3.
[/b]Hibernate Annotation[/b]语法[/b][/b]

@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;

}

}

4.
[/b]数据库表结构[/b][/b]

id
name
age
email
1
benson
21
peng@sina.com
2
laura
22
lla@163.com
5.
[/b]hibernate.cfg.xml[/b]配置文件[/b][/b]

<?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的类文件。

6.[/b]JAVA[/b]文件[/b]

HibernateSessionFactory[/b][/b]

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[/b][/b]

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!");

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: