Hibernate 优缺点
优点
1. 简化了JDBC繁琐的编码
2. 对面向对象特性支持良好,只需要操作对象,完全的面向对象思想
3. 可移植性好
4. 轻量级框架(没有侵入性)
5. 简洁的HQL编程(Hibernate Query Language)
缺点
1. 不适合需要使用数据库的特定优化机制的情况
2. Hibernate不适合批量数据的处理时
写了个小栗子 代码如下
Hibernate cfg基本配置
<hibernate-configuration>
<session-factory>
<!-- 数据库四要素 -->
<property name="connection.dirver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>
<!--数据库连接池的大小-->
<property name="hibernate.connection.pool.size">20 </property>
<!-- 数据库方言 hibernate 会根据不同的方言生成符合当前数据库规则的sql语句-->
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<!-- 显示hibernate运行时生成的sql 调试时可设置为true 项目部署后设置为false 提高效率 -->
<property name="show_sql">true</property>
<!-- 格式化sql -->
<property name="format_sql">true</property>
<!-- 当前session上下文-->
<property name="current_session_context_class">thread</property>
<!-- 注册映射文件 -->
<mapping resource="com/hbt/entity/Emp.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate hbm基本配置
<hibernate-mapping>
<class name="com.hbt.entity.Emp" table="emp" schema="scott">
<id name="empno" type="java.lang.Integer" column="empno">
<!-- 自增列生成策略
increment hibernate先查最大ID,然后在此基础上 +1
sequence DB2/Orcale 支持序列的DB
native 由hbt根据底层数据库自行决定使用哪种策略
identity 可以用于带自增长属性的DB
assigned 由程序决定 -->
<generator class="assigned"/>
</id>
<property name="ename" type="java.lang.String" column="ename"/>
<property name="job" type="java.lang.String" column="job"/>
<property name="sal" type="java.lang.Double" column="sal"/>
<property name="comm" type="java.lang.Double" column="comm"/>
</class>
</hibernate-mapping>
java junit
package com.hbt.entity;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class EmpTest {
Logger log = Logger.getLogger(this.getClass());
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
session = sessionFactory.openSession();
session.beginTransaction();
}
@After
public void tearDown() throws Exception {
session.getTransaction().commit();
}
@Test
public void test1() {
Emp emp = new Emp(124,"EMP","Student",1000.00,5000.00);
session.save(emp);
}
}
Console
Hibernate:
insert
into
scott.emp
(ename, job, sal, comm, empno)
values
(?, ?, ?, ?, ?)