一、创建java project项目
二、项目右键Configure Facets —— Install Hibernate Facet
三、项目添加对应数据库的jar包
四、编写实体类
package com.yh; public class Students { private int num; private String name; public Students() { } public Students(int num,String name) { this.num=num; this.name=name; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
五、DB Browser右键 —— new,创建数据库connection driver
六、找到数据库中对应的表右键 —— Hibernate Reverse Engineering
七、修改生成的Student.hbm.xml文件<class>的name属性为对应的实体类的路径
<hibernate-mapping> <class name="com.yh.Students" table="student" schema="dbo" catalog="Student"> <id name="num" type="java.lang.Integer"> <column name="num" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="name" length="50" /> </property> </class> </hibernate-mapping>
八、修改hibernate.cfg.xml
<hibernate-configuration> <session-factory> <!-- 指定连接数据库所用的驱动 --> <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <!-- 指定连接数据库的url,hibernate连接的数据库名 --> <property name="connection.url">jdbc:sqlserver://127.0.0.1:1433;databaseName=Student</property> <!-- 指定连接数据库的用户名 --> <property name="connection.username">sa</property> <!-- 指定连接数据库的密码 --> <property name="connection.password">12345yehuan</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property> <!-- 根据需要自动创建数据表 --> <property name="hbm2ddl.auto">update</property> <!-- 显示Hibernate持久化操作所生成的SQL --> <property name="show_sql">true</property> <!-- 将SQL脚本进行格式化后再输出 --> <property name="hibernate.format_sql">true</property> <mapping resource="mapper/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
九、编写测试类
package com.yh; import org.hibernate.*; import org.hibernate.cfg.Configuration; public class Test { public static void main(String[] args) { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Students stu = new Students(27,"叶欢"); session.save(stu); transaction.commit(); session.close(); sessionFactory.close(); } }