1. 新建一个Java的工程
2. 建立user library,名为hibernate,并导入相对应的jar包。
2.1 项目右键-->build path -->configru build path -->add library.
2.2 选择user library ,在其中新建library,叫做hibernate。
2.3 选择要导入的jar包。包括:hibernate core 3,和/required目录下的所有jar包,以及slf-nop.jar
3. 引用MySQL的jdbc驱动(jar包)。
4. 在MySQL中建立表。
5. 参考“参考文档”,建立配置文件,hibernate.cfg.xml
6. 建立student类
7. 参考“参考文档”,建立student映射文件,student.hbm.xml
8. 将student映射文件,加入hibernate.cfg.xml
9. 新建测试类,并写测试函数。
附录:
hibernate.cfg.xml的代码
student测试类代码:
2. 建立user library,名为hibernate,并导入相对应的jar包。
2.1 项目右键-->build path -->configru build path -->add library.
2.2 选择user library ,在其中新建library,叫做hibernate。
2.3 选择要导入的jar包。包括:hibernate core 3,和/required目录下的所有jar包,以及slf-nop.jar
3. 引用MySQL的jdbc驱动(jar包)。
4. 在MySQL中建立表。
5. 参考“参考文档”,建立配置文件,hibernate.cfg.xml
6. 建立student类
7. 参考“参考文档”,建立student映射文件,student.hbm.xml
8. 将student映射文件,加入hibernate.cfg.xml
9. 新建测试类,并写测试函数。
附录:
hibernate.cfg.xml的代码
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory name="java:hibernate/SessionFactory">
<!-- properties -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl">create</property
<!-- mapping files -->
<mapping resource="my/res/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
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 package="my.res">
<class name="Student" table="student">
<id name="id"></id>
<property name="name"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
student测试类代码:
public class StudentTest {
public static void main(String[] args) {
Student s = new Student();
s.setId(1);
s.setAge(20);
s.setName("zs");
Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session= sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}