Hibernate入門指南筆記
1. 首先下載Hibernate包
2. 在MySQL中建立資料庫和表
CREATE DATABASE myblog;
USE myblog;
CREATE TABLE IF NOT EXISTS cust_customer(
cust_id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '使用者id',
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(14) DEFAULT NULL COMMENT '行動電話'
);
複製程式碼
3. 匯入資料庫驅動包與Hibernate包以及日誌記錄包
3.1 匯入Hibernate包如下
3.2 匯入MySQL資料庫連線驅動包
mysql-connector-java-5.1.43-bin.jar
3.3 匯入日誌記錄包
在工程目錄下面新建一個lib目錄將所需要的包拷貝到lib資料夾下
選中所有檔案將包新增到專案中 如果新增成功,在專案檔案目錄下面會有一個Libraries包含所新增的外部庫4.在工程的src下建立一個實體,對應於資料庫中的cust_customer表
package com.whong;
public class cust_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;
}
}
複製程式碼
5.建立對映檔案
對映檔案是將剛才的實體cust_customer對映到資料庫中的 因為安裝了hibernate的外掛,所以在這裡可以直接選擇建立hbm檔案,不需要手動去配置
在這裡有可能是這樣一個包的,但是對應的不應該是這個包,需要對應於那個類cust_customer,因此需要點選Add class新增cust_customer類到這裡來 對應的hbm檔案如下<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Feb 28, 2018 2:40:14 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.whong.cust_customer" table="CUST_CUSTOMER">
<id name="cust_id" type="long">
<column name="CUST_ID" />
<generator class="assigned" />
</id>
<property name="cust_name" type="java.lang.String">
<column name="CUST_NAME" />
</property>
<property name="cust_source" type="java.lang.String">
<column name="CUST_SOURCE" />
</property>
<property name="cust_industry" type="java.lang.String">
<column name="CUST_INDUSTRY" />
</property>
<property name="cust_level" type="java.lang.String">
<column name="CUST_LEVEL" />
</property>
<property name="cust_phone" type="java.lang.String">
<column name="CUST_PHONE" />
</property>
<property name="cust_mobile" type="java.lang.String">
<column name="CUST_MOBILE" />
</property>
</class>
</hibernate-mapping>
複製程式碼
6.建立Hibernate的核心配置檔案
在第五步驟中的對映檔案反應的是持久化類和資料庫表的對映資訊,而Hibernate的配置檔案則主要是用來配置資料庫連線以及Hibernate執行時所需要的各個屬性的值,在src資料夾下建立cfg型別的檔案
在cfg配置介面這裡很關鍵需要注意 點選Get values from Connection 新建一個連線配置檔案 選擇mysql在name這裡可以標註一下以示區分連線不同的資料庫 在這裡選擇資料庫的驅動 點選這個車輪 Name/Type選擇5.1 Jar List需要移除這個驅動,點選Add JAR/Zip 選擇剛才新增進去的sql資料庫連線驅動 返回到Connection Profile這裡,修改database為myblog所對應的資料庫,同時需要注意的是,在url那裡需要新增?usessl=true
完整的url為jdbc:mysql://localhost:3306/myblog?usessl=true
7.編寫一個測試程式碼
測試程式碼如下所示
package com.testPackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.whong.cust_customer;
public class testHibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
cust_customer cust_customer = new cust_customer();
cust_customer.setCust_name("偉鴻");
cust_customer.setCust_phone("18*******969");
session.save(cust_customer);
transaction.commit();
session.close();
}
}
複製程式碼
8.試執行
如果這個時候試執行會報有如下的錯誤
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.whong.cust_customer
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:781)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1520)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:679)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:666)
at com.testPackage.testHibernate.main(testHibernate.java:21)
複製程式碼
8.1解決方案
這裡最主要的問題就是log日誌檔案的問題 解決方式是需要新增一個有關日誌的配置檔案,具體可以看一下這個連結的文章log4j WARN 和 SLF4J WARN 解決辦法 在src目錄下新增log4j.properties配置檔案
hadoop.root.logger=DEBUG, console
log4j.rootLogger=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
複製程式碼
8.2實體對映錯誤解決方式
再次執行會報如下的錯誤
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.whong.cust_customer
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:781)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1520)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:679)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:666)
at com.testPackage.testHibernate.main(testHibernate.java:21)
複製程式碼
這個問題時因為核心配置檔案cfg和實體對映檔案hbm之間沒有對應起來,所以找不到那個cust_customer實體 解決方式如下 拷貝hbm檔案的路徑
在cfg配置檔案下新增如下語句<mapping resource="/LearnHibernate/src/com/whong/cust_customer.hbm.xml"/>
但是這個地方需要去掉src前面的路徑
因此正確的路徑是
<mapping resource="com/whong/cust_customer.hbm.xml"/>
再次執行的到正確的結果 並列印如下的一些日誌記錄
18/02/28 16:21:05 INFO hibernate.Version: HHH000412: Hibernate Core {5.0.7.Final}
18/02/28 16:21:05 INFO cfg.Environment: HHH000206: hibernate.properties not found
18/02/28 16:21:05 INFO cfg.Environment: HHH000021: Bytecode provider name : javassist
18/02/28 16:21:05 INFO common.Version: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
18/02/28 16:21:05 WARN orm.deprecation: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
18/02/28 16:21:06 WARN orm.connections: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
18/02/28 16:21:06 INFO orm.connections: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/myblog?useSSL=true]
18/02/28 16:21:06 INFO orm.connections: HHH10001001: Connection properties: {user=root, password=****}
18/02/28 16:21:06 INFO orm.connections: HHH10001003: Autocommit mode: false
18/02/28 16:21:06 INFO internal.DriverManagerConnectionProviderImpl: HHH000115: Hibernate connection pool size: 20 (min=1)
18/02/28 16:21:07 INFO dialect.Dialect: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
複製程式碼
再資料庫中查詢cust_customer表也是可以查詢到這一條記錄的 至此hibernate的入門配置筆記完畢