1.运行环境:Eclipse Version: Neon Release (4.6.0)
2.安装Hibernate Tools,下载网址:http://tools.jboss.org/downloads/,看好eclipse版本。
Help > Install New Software… > Add… > Archive…
安装成功后,File->New->Other
3.添加jar包
4.新建Java Project
在项目中添加Hibernate(hibernate-release-4.2.4.Final\hibernate-release-4.2.4.Final\lib\required下所有的)
mysql的(mysql-connector-java-5.1.39-bin.jar)jar包。
(1)创建hibernate的配置文件hibernate.cfg.xml
<property name="connection.username">root</property>
<property name="connection.password">talent</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.167.4.135:3306/hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="Students.hbm.xml"/>
(2)创建持久化类
//1.公有的类
//2.提供公有的不带参数的默认的构造方法
//3.属性私有
//4.属性getter/setter封装
(3)创建对象-关系映射文件(Students.hbm.xml)
(4)通过hibernate API编写访问数据库的代码
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
.buildServiceRegistry();
// 创建会话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
// 会话对象
session = sessionFactory.openSession();
// 开启事务
transaction = session.beginTransaction();
Students students = new Students("李明", 20, "女");
session.save(students);
transaction.commit();// 提交事务
session.close();// 关闭会话
sessionFactory.close();// 关闭会话工厂