Hibernate 4.1.1的第一个例子HelloWorld (一)

2014-11-24 08:54:17 · 作者: · 浏览: 5

Hibernate 4.0与之前的3.X版本改进很很多,下面先将改动的地方说一下。


1.数据库方言设置

org.hibernate.dialect.MySQL5Dialect

在3.3版本中连接MySQL数据库只需要指明MySQLDialect即可。在4.1版本中可以指出MySQL5Dialect

2.buildSessionFactory

4.1版本中buildSessionFactory()已经被buildSessionFactory(ServiceRegistry ServiceRegistry)取代

解决办法:

Configuration cfg = new Configuration();

cfg.configure();
ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();

SessionFactory sf = cfg.configure().buildSessionFactory(serviceRegistry);

3.annotation

org.hibernate.cfg.AnnotationConfiguration;

Deprecated. All functionality has been moved to Configuration

这个注解读取配置的class已经废弃,现在读取配置不需要特别注明是注解,直接用Configuration cfg = new Configuration();就可以读取注解。

Hibernate4.1版本中推荐使用annotation配置,所以在引进jar包时把requested里面的包全部引进来就已经包含了annotation必须包了

由于Hibernate推荐使用注解,所以基于hbm的配置文件我们就不写了,而且对于新的server读取配置文件的方法建立session对于配置文件的读取貌似也有问题,我测试了好几个都没办法解决,所以这里先只介绍一下基于注解的方法了。


首先是配置文件,这个在hibernate的mannual里面可以找到

[html]
< xml version='1.0' encoding='utf-8' >
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">






com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
sa
sa



org.hibernate.dialect.MySQL5Dialect




org.hibernate.cache.internal.NoCacheProvider


true







< xml version='1.0' encoding='utf-8' >
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
sa
sa



org.hibernate.dialect.MySQL5Dialect




org.hibernate.cache.internal.NoCacheProvider


true






然后是具体的类

[java]
package com.bird.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher {

private int id;
private String name;
private String title;

@Id
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

}

package com.bird.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher {

private int id;
private String name;
private String title;

@Id
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

}

其中的表名和类名相同,其他的字段和Bean的属相相同。


最后是使用他


[java]
package com.bird.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate