Hibernate简单实例
1、配置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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- 方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 控制台显示SQL -->
<property name="show_sql">true</property>
<!-- 自动更新表结构 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/java1234/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2、配置Student.hbm.xml文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.java1234.model">
<class name="Student" table="t_student">
<id name="id" column="stuId"> <generator class="native"></generator> </id>
<property name="name"></property>
</class>
</hibernate-mapping>
3、配置好1、2步骤后写model 文件Student.java
package com.java1234.model;
public class Student {
private long id; private String name;
public long getId() { return id;
}
public void setId(long id) {
this.id = id; }
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
}
--第四步:测试:
package com.java1234.service;
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry;
import com.java1234.model.Student;
public class StudentTest {
public static void main(String[] args) {
Configuration configuration=new Configuration().configure(); // 实例化配置文件
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // 实例化服务登记 SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // 获取Session工厂
Session session=sessionFactory.openSession(); // 生成一个session
session.beginTransaction(); // 开启事务
Student s=new Student();
s.setName("张三");
session.save(s);
session.getTransaction().commit(); // 提交事务
session.close(); // 关闭session
sessionFactory.close(); // 关闭session工厂
} }
---结束