Hibernate的使用案例

一、创建hibernate.cfg.xml文件

(1)eclipse生成cfg的方法

Hibernate的使用案例_第1张图片

(2)hibernate.cfg.xml的内容

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
 <!--下面是需要填写的内容-->
  <property name="connection.username">root</property>
  <property name="connection.password">hao19890820</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
  <property name="dialect">org.hibernate.dialect.MYSQLDialect</property>
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>
  <property name="hbm2ddl.auto">create</property> 
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  
  <!--生成hbm.xml文件后再填写的内容-->
  <mapping resource="students.hbm.xml"/>
 </session-factory>
 
</hibernate-configuration>

二、创建需要与数据库交互的对象类(本次以student类为例)

 public class students {
 private int sid;
 private String sname; 
 public students(){  }

 public students(int sid, String sname) {
  this.sid = sid;
  this.sname = sname; }

 public int getSid() {
  return sid;
 }

 public void setSid(int sid) {
  this.sid = sid;
 }

 public String getSname() {
  return sname;
 }

 public void setSname(String sname) {
  this.sname = sname;
 }

}

三、生成“(对象类名).hbm.xml”文件(本案例为student.hbm.xml)

Hibernate的使用案例_第2张图片

四、将第3步生成的数据更新至第一步的配置文件

 <mapping resource="students.hbm.xml"/>

五、创建一个最终使用Hibernate的类

 public class studentsTest {
 private SessionFactory sessionFactory;
 private Session session;
 private Transaction transaction;
@Before
public void init(){
 Configuration config=new Configuration().configure(); 
 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().
   applySettings(config.getProperties()).buildServiceRegistry();
 sessionFactory=config.buildSessionFactory(serviceRegistry); 
 session=sessionFactory.openSession();
 transaction=session.beginTransaction(); 
}
@After
public void destory(){
 transaction.commit();
 session.close();
 sessionFactory.close();
}
@Test
public void test(){
 students s=new students(1,"张三丰");
 session.save(s);
}
}

你可能感兴趣的:(Hibernate)