马老师说的好。要穿一手鞋,so,自己总结下hibernate4.1版本中的新特性和hibernate3.3做区别
1.数据库方言设置
在3.3版本中连接MySQL数据库只需要指明MySQLDialect即可。在4.1版本中可以指出MySQL5Dialect
2.buildSessionFactory
4.1版本中buildSessionFactory()已经被buildSessionFactory(ServiceRegistry ServiceRegistry)取代
解决办法:
Configuration cfg = new Configuration();
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必须包了
4.Hibernate4.1已经可以自动建表,所以开发时只需要自己开发类然后配置好就OK。不需要考虑怎么建表。
1.使用hibernate.properties配置文件
以下配置的信息可以不用写在传统的hibernate.cfg.xml中了,可以写在hibernate.properties配置文件中。
hibernate.connection.driver_class=com.mysql.jdbc.driver
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate
hibernate.connection.password=root
hibernate.connection.username=root
hibernate.connection.pool_size=100
hibernate.dialect=org.hibernate.dialect.mysql5dialect
hibernate.show_sql=true
hibernate.format_sql=true
其中在3.3+版本中连接mysql数据库只需要指明mysqldialect即可。在4.1+版本中可以指出mysql5dialect。
2.sessionfactory对象的buildsessionfactory方法
4.1+版本中不带参数的buildsessionfactory()已经被废除,取而代之的是buildsessionfactory(serviceregistry serviceregistry)
为此我们采用以下方法:
public class hibernatetest {
private static sessionfactory sf = null;
@beforeclass
public static void beforeclass(){
configuration cfg = new configuration().configure();
serviceregistrybuilder srb = new serviceregistrybuilder();
//默认读取hibernate.properties里面的配置信息
sf = cfg.buildsessionfactory(srb.buildserviceregistry());
}
@afterclass
public static void afterclass(){
sf.close();
}
这里有两点需要注意
1)若使用xml配置文件的方式配置实体类:需要在代码中手动加入resource文件
(在hibernate.cfg.xml中配置已经无效
例:cfg.addresource("cn/ntt/china/model/student.hbm.xml");//须指明全路径
2)若使用注解方式:与原来3.3+版本一样在需要在hibernate.cfg.xml中加入配置即可
例:
另外org.hibernate.cfg.annotationconfiguration;(deprecated. all functionality has been moved to configuration)
这个注解读取配置的class已经废弃,现在读取配置不需要特别注明是注解。
为了适应jpa规范,hibernate4.1+版本中推荐使用annotation配置。
所以在引进jar包时把requested里面的包全部引进来就已经包含了annotation必须包了。
3.二级缓存配置
原来3.3+:
现在4.1+:
hibernate学到现在算到告一段落。现在回想下hibernate的核心思想其实就是把数据库中表与表的关系的操作,转化封装为java对象与对象的操作!那为什么要这样做呢?
原因很简单这样做符合我们日常面向对象编程的习惯,并且简化持久层操作的代码。
sun为这个思想制定了一套规范,即jpa!可见在不久的将来java持久化操作要被jpa统一。