hibernate架構:一種持久層的ORM架構
客戶管理的實體類
/**
* 客戶管理的實體類
*CREATE TABLE `cst_customer` (
`cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編号(主鍵)',
`cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',
`cust_source` varchar(32) DEFAULT NULL COMMENT '客戶資訊來源',
`cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業',
`cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級别',
`cust_phone` varchar(64) DEFAULT NULL COMMENT '固定電話',
`cust_mobile` varchar(16) DEFAULT NULL COMMENT '行動電話',
PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
*/
public class Customer {
private Long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_phone;
private String cust_mobile;
public Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
public String getCust_mobile() {
return cust_mobile;
}
public void setCust_mobile(String cust_mobile) {
this.cust_mobile = cust_mobile;
}
@Override
public String toString() {
return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_source=" + cust_source
+ ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_phone=" + cust_phone
+ ", cust_mobile=" + cust_mobile + "]";
}
}
建立實體類與表的映射,配置customer.xml,映射的配置
- 【class标簽的配置】
- 标簽用來建立類與表的映射關系
- 屬性:
- name :類的全路徑
- table :表名(類名與表名一緻,table可以省略)
- catalog :資料庫名
- 【id标簽的配置】
- 标簽用來建立類中的屬性與表中的主鍵的對應關系
- 屬性:
- name :類中的屬性名
- column :表中的字段名(類中的屬性名和表中的字段名如果一緻,column可以省略)
- length :長度
- type :類型
- 【property标簽的配置】
- 标簽用來建立類中的普通屬性與表的字段的對應關系
- 屬性:
- name :類中的屬性名
- column :表中的字段名
- length :長度
- type :類型
- not-null :設定非空
- unique :設定唯一
<?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-mapping>
<!-- 建立類與表的映射 -->
<class name="com.itheima.hibernate.demo1.Customer" table="cst_customer">
<!-- 建立類中的屬性與表中的主鍵對應 -->
<id name="cust_id" column="cust_id" >
<generator class="native"/>
</id>
<!-- 建立類中的普通的屬性和表的字段的對應 -->
<property name="cust_name" column="cust_name" length="32" />
<property name="cust_source" column="cust_source" length="32"/>
<property name="cust_industry" column="cust_industry"/>
<property name="cust_level" column="cust_level"/>
<property name="cust_phone" column="cust_phone"/>
<property name="cust_mobile" column="cust_mobile"/>
</class>
</hibernate-mapping>
在這裡使用eclipse可能會出現引用了dtd,但是在編寫配置檔案是沒有相應提示,因為這裡用的是網絡位址擷取dtd,解決方法:
打開window----preferences,輸入xml 進入xml catalog 點選add按鈕
然後将配置檔案中的網絡位址複制到key中,将keytype設定為URI,在點選file system 選擇本地下載下傳好的dtd檔案即可
hibernate核心配置:包括 必須的配置(連接配接資料庫的基本參數,方言) 可選擇的配置(顯示sql,格式化sql,自動生成資料庫等) 映射檔案(mapping标簽)
- 必須的配置
- 連接配接資料庫的基本的參數
- 驅動類
- url路徑
- 使用者名
- 密碼
- 方言 告訴Hibernate應用程式的底層即将使用哪種資料庫
- 連接配接資料庫的基本的參數
- 可選的配置
- 顯示SQL :hibernate.show_sql
- 格式化SQL :hibernate.format_sql
- 自動建表 :hibernate.hbm2ddl.auto
- none :不使用hibernate的自動建表
- create :如果資料庫中已經有表,删除原有表,重新建立,如果沒有表,建立表。(測試)
- create-drop :如果資料庫中已經有表,删除原有表,執行操作,删除這個表。如果沒有表,建立一個,使用完了删除該表。(測試)
- update :如果資料庫中有表,使用原有表,如果沒有表,建立新表(更新表結構)
- validate :如果沒有表,不會建立表。隻會使用資料庫中原有的表。(校驗映射和表結構)。
- 映射檔案的引入
- 引入映射檔案的位置<mapping resource="com/itheima/hibernate/demo1/Customer.hbm.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>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">abc</property>
<!-- 配置Hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 可選配置================ -->
<!-- 列印SQL -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化SQL -->
<property name="hibernate.format_sql">true</property>
<!-- 自動建立表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置C3P0連接配接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--在連接配接池中可用的資料庫連接配接的最少數目 -->
<property name="c3p0.min_size">5</property>
<!--在連接配接池中所有資料庫連接配接的最大數目 -->
<property name="c3p0.max_size">20</property>
<!--設定資料庫連接配接的過期時間,以秒為機關,
如果連接配接池中的某個資料庫連接配接處于空閑狀态的時間超過了timeout時間,就會從連接配接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒檢查所有連接配接池中的空閑連接配接 以秒為機關-->
<property name="c3p0.idle_test_period">3000</property>
<mapping resource="com/itheima/hibernate/demo1/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate的儲存操作
// 1.加載Hibernate的核心配置檔案
Configuration configuration = new Configuration().configure();
// 手動加載映射
// configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml");
// 2.建立一個SessionFactory對象:類似于JDBC中連接配接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 3.通過SessionFactory擷取到Session對象:類似于JDBC中Connection
Session session = sessionFactory.openSession();
// 4.手動開啟事務:
Transaction transaction = session.beginTransaction();
// 5.編寫代碼
Customer customer = new Customer();
customer.setCust_name("王西");
session.save(customer);
// 6.事務送出
transaction.commit();
// 7.資源釋放
session.close();
sessionFactory.close();
HibernateAPI
Configuration
- 作用:
- 加載核心配置檔案
- hibernate.properties
- 加載核心配置檔案
- Configuration cfg = new Configuration();
-
-
- hibernate.cfg.xml
-
- Configuration cfg = new Configuration().configure();
-
- 加載映射檔案
-
// 手動加載映射
configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml"
sessionFactory(session工廠)
SessionFactory内部維護了Hibernate的連接配接池和Hibernate的二級緩存。是線程安全的對象。一個項目建立一個對象即可。
是以,我們要抽取工具類
建立一個靜态的sessionFactory,這樣就可以控制一個項目隻建立一個sessionFactory對象
/**
* Hibernate的工具類
*/
public class HibernateUtils {
public static final Configuration cfg;
public static final SessionFactory sf;
static{
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
public static Session openSession(){
return sf.openSession();
}
}
session對象:類似于jdbc中的connection對象
Session代表的是Hibernate與資料庫的連結對象。不是線程安全的。與資料庫互動橋梁。
-
Session中的API
- 儲存方法:
- Serializable save(Object obj);
- 查詢方法:
- T get(Class c,Serializable id);
- T load(Class c,Serializable id);
- get方法和load方法的差別?
-
Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); /** * get方法 * * 采用的是立即加載,執行到這行代碼的時候,就會馬上發送SQL語句去查詢。 * * 查詢後傳回是真實對象本身。 * * 查詢一個找不到的對象的時候,傳回null * * load方法 * * 采用的是延遲加載(lazy懶加載),執行到這行代碼的時候,不會發送SQL語句,當真正使用這個對象的時候才會發送SQL語句。 * * 查詢後傳回的是代理對象。javassist-3.18.1-GA.jar 利用javassist技術産生的代理。 * * 查詢一個找不到的對象的時候,傳回ObjectNotFoundException */ // 使用get方法查詢 /*Customer customer = session.get(Customer.class, 100l); // 發送SQL語句 System.out.println(customer);*/ // 使用load方法查詢 Customer customer = session.load(Customer.class, 200l); System.out.println(customer); tx.commit(); session.close();
- 修改方法
- void update(Object obj);
-
Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); // 直接建立對象,進行修改 /*Customer customer = new Customer(); customer.setCust_id(1l); customer.setCust_name("王聰"); session.update(customer);*/ // 先查詢,再修改(推薦) Customer customer = session.get(Customer.class, 1l); customer.setCust_name("王小賤"); session.update(customer); tx.commit(); session.close();
- 删除方法
- void delete(Object obj);s
-
Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); // 直接建立對象,删除 /* Customer customer = new Customer(); customer.setCust_id(1l); session.delete(customer);*/ // 先查詢再删除(推薦)--級聯删除 Customer customer = session.get(Customer.class, 2l); session.delete(customer); tx.commit(); session.close();
- 儲存或更新
- void saveOrUpdate(Object obj)
-
Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); /*Customer customer = new Customer(); customer.setCust_name("王鳳"); session.saveOrUpdate(customer);*/ Customer customer = new Customer(); customer.setCust_id(3l); customer.setCust_name("李如花"); session.saveOrUpdate(customer); tx.commit(); session.close();
- 查詢所有
-
Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); // 接收HQL:Hibernate Query Language 面向對象的查詢語言 /*Query query = session.createQuery("from Customer"); List<Customer> list = query.list(); for (Customer customer : list) { System.out.println(customer); }*/ // 接收SQL: SQLQuery query = session.createSQLQuery("select * from cst_customer"); List<Object[]> list = query.list(); for (Object[] objects : list) { System.out.println(Arrays.toString(objects)); } tx.commit(); session.close();
- 儲存方法:
Transaction(事務對象)
Hibernate中管理事務的對象。
- commit();
- rollback();