hibernate入门之person表

时间:2023-03-08 22:41:36
hibernate入门之person表

下面的hibernate入门person表指的是:根据mysql数据库中的test表和其中的元素--》建立映射表==》进而创建持久化类的顺序来操作了,下面为步骤

1.配置MySQL驱动程序

  这一步操作是为了使用hibernate自动生成xml文件时设置里面参数使用的。(其实也可以略去,直接在hibernet工程中添加mysql的jdbc的jar包就可以了).

  1.1使用myeclipse:preferences配置来mysql的驱动程序步骤如下:

  在MyEclipse中,点击Window ->Preferences->MyEclipse -> Database Explorer -> Datebase Drivers,此时可以看到右边框中蓝色下划线字体:DB Browser,点击就可在工程的项目栏中出现DB Brower显示框了(实际上这个可以在其他地方点击也可以出来)。

  1.2 建立mysql驱动

    右键选择:new->Database Driver->

      Driver template 为:MySQL Connector/J;

      URL为: jdbc:mysql://localhost:3306/hibernate,其中hibernate为数据库名称(根据自己的数据库改);

      user name:mysql用户名

      password:密码

      Driver jars:jdbc连接mysql的驱动包,点击右边的add选择,添加进去

    上面都设置成功了之后,把密码保存下来,点击进行Test Driver,如果测试成功说明驱动设置成功了,点击ok

 

2.用Myeclipse向导添加hibernate的jar包和配置文件

 2.1 创建hibernate工程

  就是new一个普通的java普通工程。

 2.2 使用Myeclipse向导添加

  这个项目添加hibernate必要的文件.在我们项目名上点击右键,选择MyEclipes --> Add Hibernate Capabilities...弹出对话框如下图:

  hibernate入门之person表

  其中,JAR Library Installation 选为 Copy checked Library Jars to Project …项(这个就是说明把jar包先拷贝到lib下面,在添加到build path里面,用add最好,省空间),其它项均为默认,点击Next,进入下一个页面后,继续点击Next,进入第三个页面

  hibernate入门之person表

  这个地方就用到了第一步中设置的mysql驱动(版本不一样,我的版本是DB Driver,早起版本是DB profile),选择第一步设置的驱动:zyfMysqlDriver(如果手动录入的话也可以,不过mysql的驱动你还需要再次手动添加到build path中),点击next

  hibernate入门之person表

  这个地方一般默认即可,这样会自动生成配置文件:hibernagte.cfg.xml和hibernateSessionFactory.java,不过本次把勾去掉,就不会再生成hibernateSessionFactory.java文件了。

3. 准备mysql的表

  实现准备mysql中建立数据表

  我在test库中建person表如下: 

 hibernate入门之person表

4.工程源码部分

 4.1hibernagte.cfg.xml内容

  hibernagte.cfg.xml是hibernate配置文件,myeclipse会自动为我们生成的源码如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">zyfMysqlDriver</property> </session-factory> </hibernate-configuration>

4.2 建立持久化类

源码如下:

package com.zyf.hibernate.bean;

/**
* Person entity.
*
* @author MyEclipse Persistence Tools
*/ public class Person implements java.io.Serializable { private int id;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}

4.3 建立映射文件

 映射文件Person.hbm.xml文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<!--
person持久化类对应于数据库的表示person表
-->
<class name="com.zyf.hibernate.bean.Person" table="person" >
<!--
id :用来标明主键的
name:指持久化类中的属性
column:在数据库person表中,主键的那个字段
type:hibernate类型 或者java类型
-->
<id name="id" type="integer" column="id">
<!--
主键的生成器
assigned表示主键是有程序来生成的
-->
<generator class="assigned"></generator>
</id>
<property name="name" column="name" type="java.lang.String"></property>
<property name="sex" column="sex" type="java.lang.String"></property>
</class>
</hibernate-mapping>

4.4 配置文件中引入映射文件

就是在hibernagte.cfg.xml引入Person.hbm.xml映射文件,引入之后的hibernagte.cfg.xml如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">zyfMysqlDriver</property> <mapping resource="com/zyf/hibernate/bean/Person.hbm.xml"/>
</session-factory> </hibernate-configuration>

注意上面resource内容路径的写法。

4.5. 编写测试类

代码如下:

package com.zyf.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.zyf.hibernate.bean.Person; public class PersonTest { @Test
public void testSave(){
/*
* configuration这个类的作用就是用来加载 hibernate的配置文件
* hibernate的事务不是自动提交的
*/
Configuration configuration = new Configuration();
configuration.configure(); //sessionfactory 相当于jdbc的connection
SessionFactory sessionfactory= configuration.buildSessionFactory(); Person person = new Person();
person.setId(1);
person.setName("男一号");
person.setSex("男");
Session session =sessionfactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(person);
transaction.commit();
session.close();
}
}

  注:编写测试类的时候要需要junit库的支持,添加库的方法:右键工程,选择build path->config build path->libraries->add library->junit->unit4,finish.

4.6 验证

  最后在person表中出现了数据,如下:

  hibernate入门之person表

  说明验证成功

5.补充修改和删除的测试代码

  

@Test
public void testUpdate(){
/*
* configuration这个类的作用就是用来加载 hibernate的配置文件
* hibernate的事务不是自动提交的
*/
Configuration configuration = new Configuration();
configuration.configure(); //sessionfactory 相当于jdbc的connection
SessionFactory sessionfactory= configuration.buildSessionFactory();
Session session =sessionfactory.openSession();
Transaction transaction = session.beginTransaction(); Person person =(Person)session.get(Person.class, 1);
person.setName("王五");
person.setSex("女");
session.update(person);
transaction.commit();
session.close();
} @Test
public void testDelete(){
/*
* configuration这个类的作用就是用来加载 hibernate的配置文件
* hibernate的事务不是自动提交的
*/
Configuration configuration = new Configuration();
configuration.configure(); //sessionfactory 相当于jdbc的connection
SessionFactory sessionfactory= configuration.buildSessionFactory();
Session session =sessionfactory.openSession();
Transaction transaction = session.beginTransaction(); Person person =(Person)session.get(Person.class, 1);
session.delete(person);
transaction.commit();
session.close();
}

6.使用HibernateSessionFactory操作的代码

  HibernateSessionFactory是myeclipse在向导中给我们生成的一个类,如果使用这个类的话,开发会更好一些,下面基于这个类对testSave()改进的话,如下:

  

    @Test
public void testSave(){
/*
* configuration这个类的作用就是用来加载 hibernate的配置文件
*/
Session session = HibernateSessionFactory.getSession();
Person person = new Person();
person.setName("男一号");
person.setSex("男");
person.setId("402881e43261e2a3013261e2db930001");
Transaction transaction = session.beginTransaction(); session.save(person);//因为主键的生成机制为increment,所以应该是在主键最大值的基础上加1,当执行session.save时,发出寻找主键的最大值的sql语句
//session.flush();//把session中的对象同步到数据库中 person.setSex("女");
person.setName("女一号");
session.close();
}

  可以发现前面很多拉杂的地方,他一行代码就可以搞定

  Session session = HibernateSessionFactory.getSession();

  分析HibernateSessionFactory.getSession()函数代码即可知道,他是从当前的ThreadLocal中获取session,比原来的安全的多。