1、首先打开myeclipse,建一个Java Project,导入Hibernate所需要的jar包及mysql数据库驱动的jar;
需要的jar请参考博文 http://blog.csdn.net/spring292713/article/details/8119159
新建数据库 Hibernate。
2、新建 POJO类,Student.java
package com.hibernate._0100_introduce; public class Student { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
3、新建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> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3308/hibernatexml</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/hibernate/_0100_introduce/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
4、编写Student.hbm.xml文件
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hibernate._0100_introduce.Student" table="Student"> <id name="id" column="Sno"> <generator class="native" /> </id> <property name="name" column= "Sname"/> <property name="age" /> </class> </hibernate-mapping>
column属性指定字段在数据库表中的名称,若不指定,默认与类中的属性名一样;
5、在hibernate.cfg.xml文件中添加Student.hbm.xml配置文件,上面的配置文件已加入。
6、编写测试类Test.java
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Test { public static void main(String[] args) { Student s = new Student(); s.setName("zhangsan"); s.setAge(8); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close; } }