Hibernate4学习之HelloWorld(一)
程序员文章站
2022-04-14 09:18:17
...
Hibernate4:开源的对象关系映射框架(ORM)
hibernate4:入门实例
1.hibernate官网下载hibernate4源码,在项目中引入lib/required目录下的全部包(10个)和数据库驱动包
2.连接mysql,创建数据库hibernate
3.配置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/newbeedaly/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.创建Student类和Student.hbm.xml文件,在hibernate.cfg.xml引入。
package com.newbeedaly.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;
}
}
<?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.newbeedaly.model">
<class name="Student" table="t_student">
<id name="id" column="stuId">
<generator class="native"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
5.创建Student测试类
package com.newbeedaly.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.newbeedaly.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工厂
}
}
运行测试类测试。
上一篇: Hibernate4学习(一)入门