初步体验Hibernate
1)创建WEB项目
2)添加Hibernate库和相关数据库JAR包放到项目中
3)创建JAVA Bean业务实体类
4)创建实体类映射的配置文件:***.hbm.xml
5)创建Hibernate配置文件Hibernate.cfg.xml
6)创建Dao类实现添加一个条数据
7)创建BIZ类调用DAO类
8)创建JSP页面,调用BIZ类,实现添加一条数据功能
9)部署,运行
实体类数据映射文件UserInfo.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="entity"><class name="MyUser" ><id name="userId"> <generator class="native"/></id><property name="userName"/><property name="userPwd"/><property name="gender"/></class></hibernate-mapping>
Hibernate配置文件Hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 显示打印执行的SQL语句命名 --><property name="show_sql">true</property><!-- 格式化打印SQL语句 --><property name="format_sql">true</property><!-- 配置数据库参数 --><!-- 配置数据库方言 --><property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property><!-- 数据库驱动 --><property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property><property name="hibernate.connection.username">bam</property><property name="hibernate.connection.password">bam</property><!-- 设置数据定义语言操作的方式 --><property name="hibernate.hbm2ddl.auto">update</property><!-- 加载对象关系映射文件 --><mapping resource="entity/MyUser.hbm.xml"/></session-factory></hibernate-configuration>
Hibernate基本操作代码
// 初始化配置文件,并读取配置文件信息Configuration configuration = new Configuration().configure();// 注册器,通过配置文件信息注册信息ServiceRegistryBuilder srb = new ServiceRegistryBuilder().applySettings(configuration.getProperties());// 创建会话工厂SessionFactory sessionFact = configuration.buildSessionFactory(srb.buildServiceRegistry());// 开启会话Session session = sessionFact.openSession();// 开启事务Transaction transaction = session.beginTransaction();// 保存数据session.save(user);// 提交事务transaction.commit();// 关闭会话session.close();