1. 程式人生 > >Hibernate基礎例項

Hibernate基礎例項

hibernate是orm(物件關係對映)框架 即通過配置檔案使物件與資料庫表關聯

讓eclipse斷網擁有xml提示功能

①解壓hibernate-core-5.0.7.Final.jar

②進入org\hibernate下複製到單獨檔案
//此處演示配置單個 其餘配置同理
hibernate-configuration-3.0.dtd
hibernate-configuration-4.0.xsd
hibernate-mapping-3.0.dtd
hibernate-mapping-4.0.xsd

③開啟hibernate-mapping-3.0.dtd 複製xml文件型別標記裡的uri
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

hibernate的所有配置檔案模板都在 hibernate-release-5.0.7.Final\project\etc

ehcache.xml
hibernate-service.xml
hibernate.cfg.xml
hibernate.properties
hibernate.properties.template
log4j.properties


hibernate例項

①匯入hibernate包

//匯入hibernate必選包&資料庫連線包
antlr-2.7.7.jar
dom4j-1.6.1.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.0.7.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-2.0.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.3.0.Final.jar

mysql-connector-java-5.1.7-bin.jar

②建立customer表

CREATE TABLE `customer` (
`id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)',
`name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',
`source` varchar(32) DEFAULT NULL COMMENT '客戶資訊來源',
`industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業',
`level` varchar(32) DEFAULT NULL COMMENT '客戶級別',
`linkman` varchar(64) DEFAULT NULL COMMENT '聯絡人',
`phone` varchar(64) DEFAULT NULL COMMENT '固定電話',
`mobile` varchar(16) DEFAULT NULL COMMENT '行動電話',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


③建立實體類Customer

//建立實體類與customer表對應 類名=表名字 屬性名=表字段名
public class Customer {
private Long id;
private String name;
private String source;
private String industry;
private String level;
private String linkman;
private String phone;
private String mobile;
//getter setter
//框架呼叫無參構造方法例項物件 構造方法沒有過載時可預設不寫jvm會補充
}

④建立物件與表對映檔案Customer.hbm.xml 和實體類放置同包

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 配置表與實體物件的關係 -->
<!-- package屬性:填寫包名 在元素內部需書寫完整類名的屬性 可直接去掉包名 -->
<hibernate-mapping package="com.java.entity" >
<!--
class元素:配置實體與表的對應關係
name:完整類名
table:資料庫表名
-->
<class name="Customer" table="customer" >
<!-- id元素:配置主鍵對映的屬性
name:填寫主鍵對應屬性名
column(可選):填寫表中的主鍵列名 預設值:列名會預設使用屬性名
type(可選):填寫列(屬性)的型別 hibernate會自動檢測實體的屬性型別
每個型別有三種填法:java型別|hibernate型別|資料庫型別
not-null(可選):配置該屬性(列)是否不能為空 預設值:false
length(可選):配置資料庫中列的長度 預設值:使用資料庫型別的最大長度
-->
<id name="id" >
<!-- generator:主鍵生成策略 -->
<generator class="native"></generator>
</id>
<!-- property元素:除id之外的普通屬性對映
name:填寫屬性名
column(可選):填寫列名
type(可選):填寫列(屬性)的型別 hibernate會自動檢測實體的屬性型別
有三種填法:
type元素
java型別[java.lang.String...]
hibernate型別[string...]
sql-type元素
資料庫型別[varchar...]
not-null(可選):配置該屬性(列)是否不能為空 預設值:false
length(可選):配置資料庫中列的長度 預設值:使用資料庫型別的最大長度
-->
<property name="name" column="name" >
<!-- <column name="name" sql-type="varchar" ></column> -->
</property>
<property name="source" column="source" ></property>
<property name="industry" column="industry" ></property>
<property name="level" column="level" ></property>
<property name="linkman" column="linkman" ></property>
<property name="phone" column="phone" ></property>
<property name="mobile" column="mobile" ></property>
</class>
</hibernate-mapping>

⑤建立hibernate主配置檔案 路徑在src下 名字為hibernate.cfg.xml(預設配置)

<?xml version="1.0" encoding="UTF-8"?>
<!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>
<!-- 資料庫驅動 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 資料庫url -->
<property name="hibernate.connection.url">jdbc:mysql:///test</property>
<!-- 資料庫連線使用者名稱 -->
<property name="hibernate.connection.username">root</property>
<!-- 資料庫連線密碼 -->
<property name="hibernate.connection.password">root</property>
<!--
資料庫方言
不同資料庫sql語法略有區別 指定方言可讓hibernate框架針對區別生成sql語句
sql99標準(通用語法):
DDL 定義語言 庫&表的增刪改查
DCL 控制語言 事務&許可權
DQL 查詢語言 資料查詢
DML 操縱語言 資料增刪改
注意:MYSQL在選擇方言時 選擇MySQLDialect 通用狀態
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- 將hibernate生成的sql語句列印到控制檯 -->
<property name="hibernate.show_sql">true</property>
<!-- 將hibernate生成的sql語句格式化(語法縮排) -->
<property name="hibernate.format_sql">true</property>
<!--
## auto schema export 自動匯出表結構 自動建表
#hibernate.hbm2ddl.auto create 自動建表 每次框架執行都會建立新的表 以前表將會被覆蓋 表資料會丟失(開發時測試使用)
#hibernate.hbm2ddl.auto create-drop 自動建表 每次框架執行結束都會將所有表刪除(開發時測試使用)
#hibernate.hbm2ddl.auto update 自動生成表 如果已經存在不會再生成 如果表有變動 自動更新表資料|欄位(對資料庫無資料影響)
#hibernate.hbm2ddl.auto validate 校驗 不生成表 每次啟動會校驗資料庫中表是否正確 校驗失敗報錯
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 引入對映檔案路徑填寫src下的路徑 -->
<mapping resource="com/java/entity/Customer.hbm.xml" />

</session-factory>
</hibernate-configuration>

測試框架例項

public class Test {
public static void main(String[] args) {
Configuration configuration= new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setName("TestName");
session.save(c);//執行儲存
transaction.commit();
session.close();
sessionFactory.close();
}
}

select * from customer;

+----+----------+--------+----------+-------+---------+-------+--------+
| id | name | source | industry | level | linkman | phone | mobile |
+----+----------+--------+----------+-------+---------+-------+--------+
| 1 | TestName | NULL | NULL | NULL | NULL | NULL | NULL |
+----+----------+--------+----------+-------+---------+-------+--------+

hibernate常用api

public class Test {
public static void main(String[] args) {
// 建立框架配置物件
Configuration configuration = new Configuration();

// 讀取指定主配置檔案 空參加載方法預設載入src下的hibernate.cfg.xml檔案
configuration.configure();

// 讀取指定類對映xml檔案 如主配置中已引入對映配置 不需要手動載入
// configuration.addResource(resourceName);
// configuration.addClass(persistentClass);

// 根據配置資訊 建立SessionFactory物件 此類執行緒安全序列執行建議只有一個例項
SessionFactory sessionFactory = configuration.buildSessionFactory();

// 獲得session物件
Session session = sessionFactory.openSession();

// 只獲得操作事務的Transaction物件
// Transaction transaction = session.getTransaction();
// 獲得Transaction物件並開啟事務(建議使用)
Transaction transaction = session.beginTransaction();

/*
* 根據Customer的id去查詢使用者 1l代表Customer的id型別為long值為1
* Customer customer = session.get(Customer.class, 1l);
* System.out.println(customer);
*/

/*
* 增加單個使用者
* Customer customer = new Customer();
* customer.setName("User");
* 執行save
* session.save(customer);
*/

/*
* 獲得要修改的物件
* Customer customer = session.get(Customer.class, 1l);
* 修改成功後的資料
* customer.setName("Test");
* 執行update
* session.update(customer);
*/

/*
* 獲得要刪除的物件
* Customer customer = session.get(Customer.class, 1l);
* 執行delete
* session.delete(customer);
*/

//transaction.rollback();// 回滾事務
transaction.commit();// 提交事務
session.close();// 釋放資源
sessionFactory.close();// 釋放資源
}
}

hibernate工具類

public class HibernateUtils {
private static SessionFactory sessionFactory;

static{
// 預設載入src下的hibernate.cfg.xml建立hibernate配置物件
Configuration configuration= new Configuration().configure();
// 根據配置資訊 建立SessionFactory物件
sessionFactory = configuration.buildSessionFactory();
}

//獲得session物件
public static Session openSession(){
// 獲得session
Session session = sessionFactory.openSession();
return session;
}
}