3.Hibernate入門筆記

Hibernate入門指南筆記html

1. 首先下載Hibernate包

Hibernate5.0.7java

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.jarmysql

3.3 導入日誌記錄包

在工程目錄下面新建一個lib目錄將所須要的包拷貝到lib文件夾下 git

選中全部文件將包添加到項目中
若是添加成功,在項目文件目錄下面會有一個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文件,不須要手動去配置 github

在這裏有多是這樣一個包的,可是對應的不該該是這個包,須要對應於那個類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類型的文件 sql

在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.試運行

若是這個時候試運行會報有以下的錯誤apache

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配置文件bash

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實體映射錯誤解決方式

再次運行會報以下的錯誤session

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的入門配置筆記完畢

WiHongNoteBook

相關文章
相關標籤/搜索