標籤:
1.構建了一個Student實體類
public class Student {
private Integer id;
//name
private String name;
//age
private Integer age;
}
2.構建一個大配置
在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="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">sb</property>
<property name="connection.password">sb</property>
<!-- 輸出所有 SQL 陳述式到控制台。 -->
<property name="hibernate.show_sql">true</property>
<!-- 在 log 和 console 中列印出更漂亮的 SQL。 -->
<property name="hibernate.format_sql">true</property>
<!-- 方言 -->
<property name="hibernate.dialect"> org.hibernate.dialect.Oracle10gDialect</property>
<!-- 關聯小配置 -->
</session-factory>
</hibernate-configuration>
3.構建小配置,和實體類對應的
Student.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 package="cn.happy.entity">
<class name="Student" table="Student">
<id name="id" type="int" column="id">
</id>
<property name="name" type="string" column="name"/>
<property name="age" type="int" column="age"/>
</class>
</hibernate-mapping>
4.測試代碼
對session進行探究。
Session.save(stu);
package cn.happy.test;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.Test;
import cn.happy.entity.Student;
public class H_01Test {
@Test
public void testAdd(){
//1.1構建一個學生對象
Student stu=new Student();
stu.setAge(18);
stu.setName("2016年8月28日09:21:09訓練營");
stu.setId(3);
//1.2 找到和資料庫的介面 xxx========session--->sessionFactory--->configure.buildSessionFactory()
//咱們要想打通和db通道
Configuration cf=new Configuration().configure("hibernate.cfg.xml");
SessionFactory factory = cf.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
//1.3儲存
session.save(stu);
tx.commit();
session.close();
}
}
第四章 Hibernate入門