1、hibernate基本概念
Hibernate 的意思是“冬眠”
在Java中的作用和它本来的意思没有太大的关联。
在MVC开发模式中,Struts是视图层的框架,
Hibernate是帮助我们更容易地和数据库打交道的,是属于模型层的框架。
ORMapping的概念
Object:程序对象
Relationship:数据库表(关系型数据库)RDBMS
Mapping:映射
ORMapping,像操作对象一样,来操作数据库
举例:
Student student=new Student();
student.name="Mike";
student.age="20";
session.save(student);
其他的ORMapping框架:TopLink,JDO
数据库其他框架:mybatis
2、下载地址http://hibernate.org/
3、导入jar包及配置
(1)添加hibernate的jar包 lib/required
(2)添加struts2的jar包 apps/解压一个项目blank/lib
(3)添加mysql数据库连接驱动
(4)添加struts2的配置文件struts.xml 在apps\struts2-blank\WEB-INF\src\java目录下找,复制到src目录下
(5)添加hibernate的配置文件hibernate.cfg.xml 在project/etc 目录下找,复制到src目下
到documentation\userguide 目录下找配置连接参考。
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/curricula</property>
<property name="connection.username">root</property>
<property name="connection.password">12345678</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
hbm2ddl.auto 是否自动创建数据库
4、测试
在hibernate.cfg.xml里改一个存在的数据库名再进行测试。
建立text. jsp 导入包,out.print(HibernateUtil.openSession());
建common包,HibernateUtil.java
编写初始化SessionFactory和获取Session的代码:SessionFactory:连接池 Session:连接
HibernateUtil.java代码如下
package common;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static Session openSession() {
return getSessionFactory().openSession();
}
}