SSH整合步驟五、單獨配置Hibernate

先單獨配置Hibernate,驗證是否正確後再進行整合。

  • 1、先簡單寫一個實體類

public class TestMain {
	
	private Integer id;
	private String name;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
  • 然後書寫該類的hibernate實體配置文件(文件名一般爲:類名.hbm.xml,如TestMain.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">
<hibernate-mapping>
	<!-- 配置實體對應表 -->
	<class name="com.hh.domain.TestMain" table="test">
		<!-- 配置主鍵 -->
		<id name="id" column="id">
			<!-- 配置主鍵生成策略 -->
			<generator class="native"></generator>
		</id>
		<!-- 配置列 -->
		<property name="name"></property>
		
	</class>
</hibernate-mapping>

書寫Hibernate主配置文件:

<?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.cj.jdbc.Driver</property>
		 <!-- 數據庫路徑 ————三道斜槓///相當於//localhost-->
		<property name="hibernate.connection.url"><![CDATA[jdbc:mysql:///hibernate_crm?allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8&useSSL=false]]></property>
		 <!-- 數據庫連接用戶名 -->
		<property name="hibernate.connection.username">root</property>
		 <!-- 數據庫連接密碼 -->
		<property name="hibernate.connection.password">123123</property>
		 <!-- 數據庫方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		
		<!-- 配置顯示sql語句和格式化sql語句 -->
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		
		<!-- 對錶操作方式配置update——先查詢是否有表,沒有則新建,有則直接用 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 配置實體映射  -->
		<mapping resource="com/hh/domain/TestMain.hbm.xml" />		
	</session-factory>
</hibernate-configuration>

書寫代碼測試:

	@Test
	public void testHiber() {
		// 創建讀取配置文件的對象,並讀取配置文件
		Configuration cf = new Configuration().configure();
		// 創建Session工廠
		SessionFactory sf = cf.buildSessionFactory();
		// 創建Session
		Session session = sf.openSession();
		// 開啓事務
		Transaction tst = session.beginTransaction();
		// 創建對象
		TestMain tm = new TestMain();
		tm.setName("test");
		// 持久化對象
		session.save(tm);
		// 事務提交、關閉資源
		tst.commit();
		session.close();
		sf.close();
	}

執行成功時,控制檯會打印sql語句:

因爲沒有手動建表,所以Hibernate自動幫忙創建了表,到數據庫中檢查是否執行成功:

執行成功,說明Hibernate基本配置完成了,可以進行下一步了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章