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();
}
}