Hibernate的優/缺點
優點:1.Hibernate是一個沒有侵入性的架構,沒有侵入性的架構我們稱為輕量級架構。
2.更加對象化 3.移植性 4.Hibernate代碼測試友善。 5.提高效率,提高生産力。
缺點: 1.使用資料庫特性的語句,将很難調優
2.對大批量資料更新存在問題
3.系統中存在大量的攻擊查詢功能
Hibernate六大核心接口
1.Configuration接口:負責配置并啟動Hibernate
2.SessionFactory接口:負責初始化Hibernate
3.Session接口:負責持久化對象的CRUD操作
4.Transaction接口:負責事務
5.Query接口和Criteria接口:負責執行各種資料庫查詢
注意:Configuration執行個體是一個啟動期間的對象,一旦SessionFactory建立完成它就被丢棄了。

所需Hibernate包的連結:https://pan.baidu.com/s/10CQ_FvSkagqLG_JU0KBjHg
提取碼:sl72
1.主映射檔案hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate_emp1?characterEncoding=utf-8
</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- 顯示hql語句 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 映射檔案 -->
<mapping resource="com/aiit/pojo/TblEmp.hbm.xml" />
</session-factory>
</hibernate-configuration>
2.封裝hibernate.cfg.xml
package com.aiit.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}
3.員工類TblEmp.java
package com.aiit.pojo;
public class TblEmp implements java.io.Serializable {
// Fields
private Integer empId;
private String empName;
// Constructors
/** default constructor */
public TblEmp() {
}
/** full constructor */
public TblEmp(String empName) {
this.empName = empName;
}
// Property accessors
public Integer getEmpId() {
return this.empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return this.empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
4.類的映射檔案TblEmp.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.aiit.pojo.TblEmp" table="tbl_emp" catalog="hibernate_emp1">
<!-- 類屬性名和資料庫表字段名進行映射 -->
<!--id name指類的主屬性名,type屬性類型 -->
<id name="empId" type="java.lang.Integer">
<!--column name指對應的資料庫表字段名 -->
<column name="empId" />
<!-- generator 主鍵 設定 -->
<generator class="identity" />
</id>
<property name="empName" type="java.lang.String">
<column name="empName" />
</property>
</class>
</hibernate-mapping>
5.單元測試類TestEmp.java
package com.aiit.test;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.aiit.pojo.TblEmp;
import com.aiit.utils.HibernateSessionFactory;
public class TestEmp {
static Session session;
static Transaction tx;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
session = HibernateSessionFactory.getSession();
tx = (Transaction) session.beginTransaction();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
session.close();
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void selectOne() {
//查詢
TblEmp emp = (TblEmp) session.get(TblEmp.class, 1);
System.out.println(emp.getEmpName());
}
@Test
public void addEmp() {
//添加
TblEmp emp2=new TblEmp("ait1");
tx.begin();
session.save(emp2);
tx.commit();
}
@Test
public void selectAll() {
//查詢所有
String hql = "from TblEmp";//from 類名,這裡不再使用sql,實作編碼語言與背景資料庫分離。
List<TblEmp> emps = session.createQuery(hql).list();
for(TblEmp emp :emps){
System.out.println("工号"+emp.getEmpId()+"姓名"+emp.getEmpName());
}
}
@Test
public void selectWhere() {
//條件查詢
String hql = "from TblEmp as emp where emp.empId>2";
List<TblEmp> emps = session.createQuery(hql).list();
for(TblEmp emp :emps){
System.out.println("工号"+emp.getEmpId()+"姓名"+emp.getEmpName());
}
}
@Test
public void selectSql() {
//sql語句查詢
String sql = "SELECT * FROM tbl_emp";
List<Object> emps = session.createSQLQuery(sql).list();
for(int i = 0;i<emps.size();i++){
Object[] employee = (Object[]) emps.get(i);
System.out.println(employee[0]+","+employee[1]);
}
}
@Test
public void deleteOne() {
//删除
TblEmp emp = (TblEmp) session.get(TblEmp.class, 2);
tx.begin();
session.delete(emp);
tx.commit();
}
@Test
public void UpdateOne() {
//修改
TblEmp emp = (TblEmp) session.get(TblEmp.class, 2);
emp.setEmpName("北方");
tx.begin();
session.update(emp);
tx.commit();
}
}
6.資料庫SQL
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tbl_emp
-- ----------------------------
DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp` (
`empId` int(11) NOT NULL AUTO_INCREMENT,
`empName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`empId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of tbl_emp
-- ----------------------------
INSERT INTO `tbl_emp` VALUES (1, '北方');
INSERT INTO `tbl_emp` VALUES (2, '小明');
INSERT INTO `tbl_emp` VALUES (3, '小紅');
INSERT INTO `tbl_emp` VALUES (4, 'AIIT');
SET FOREIGN_KEY_CHECKS = 1;