Java学习笔记之Hibernate-Hibernate入门和单表增删改查

来源:互联网 发布:如何提高淘宝店信誉 编辑:程序博客网 时间:2024/06/06 19:26

在此楼主只是为了记录自己的学习轨迹,将自己学习的一些认识和看法记录下来,如果有能帮助到网友的最好,如果写的不好或有错误请多多谅解并欢迎指正。
1、hibernate是对JDBC进行了封装,是一个ORM(Object RelationShip Mapping)框架,自动生成sql语句。
2、hibernate官网:http://hibernate.org/ ,当然下载是免费的。下载完成的是一个压缩文件,解压之后会出现类似如下的目录结构(我下的是hibernate-release-5.2.10.Final)
这里写图片描述
在lib文件夹下有我们需要的jar包,目录结构如下所示
这里写图片描述
required文件夹里面是必须的jar包,其它文件夹里面的jar包是有自己其它功能的,有需要再导入。关于required里面的jar包每个是什么功能以后详细说明。在此只是进行hibernate的入门操作。
3、Hibernate的入门前奏1:因为hibernate是对jdbc的封装,所以要和数据库打交道,我用的数据库是MySQL,别的数据库电脑没有装。
MySQL数据库进行一些操作,建立个库叫test,在test库建立个表叫student,student表里面有两个属性,分别是sid和name,sid是主键,并把编码设置为utf8,免得乱码。

CREATE DATABASE 'test';USE test;DROP TABLE IF EXISTS `student`;CREATE TABLE `student` (  `sid` int(11) NOT NULL,  `name` varchar(255) DEFAULT NULL,  PRIMARY KEY (`sid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4、hibernate入门前奏2:
认识hibernate的相关类
org.hibernate.Session 这个类就相当于数据库连接,类似于JDBC里面的Connection
org.hibernate.SessionFactory 这个类是产生Session的工厂
org.hibernate.Transaction 这个类是Hibernate的事务对象,对数据库的操作基本都在事务下进行的
开发环境:eclipse或MyEclipse,其他的我没用过
导入hibernate的jar包,因为和MySQL数据库连接,所以也导入MySQL和java连接的jar包
5、hibernate的入门操作
5.1 在src目录下新建一个xml文件,名称为hibernate.cfg.xml 这是hibernate全局配置文件

<?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"><hibernate-configuration><session-factory>    <!-- 配置数据库驱动类 -->    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>    <!-- 配置数据库url -->    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>     <!-- 配置数据库用户名 -->    <property name="connection.username">root</property>     <!-- 配置数据库密码 -->    <property name="connection.password">root</property>    <!-- 配置SQL方言 每个数据库都有自己独有的sql语句,使用的是mysql,所以配置mysql的方言 -->    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>    <!-- 在控制台输出sql语句 可配置可不配置 配置了就是想在控制台看一下生成的sql语句是什么样的 -->    <property name="show_sql">true</property>    <!-- 在启动时根据配置更新数据库 配置可不配置 配置了就是想如果数据库没有我们这个表 我们就创建或更新这个表 -->    <property name="hbm2ddl.auto">update</property>    <!-- 这个mapping 可以最后配置 用来注册我们的实体映射类 让hibernate知道我们哪个类对应哪个表-->   <mapping resource="com/Student.hbm.xml" /></session-factory></hibernate-configuration>

5.2 在创建类com.Student 对应我们数据库中student表

public class Student  {    private int id;    private String name;    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 Student(int id, String name) {        this.id = id;        this.name = name;    }    public Student() {    }    @Override    public String toString() {        return "Student [id=" + id + ", name=" + name + "]";    }}

5.3 在Student类同一个包下创建一个xml文件用来配置Student类和数据库的student表,这个xml文件叫做Student.hbm.xml(当然也可以用注解的方式配置,在此只介绍用hbm.xml方式配置),在Student.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"><hibernate-mapping>    <!--name属性写包名加类名 table写的是数据库中和这个类对应的表的名字 -->    <class name="com.Student" table="student">    <!--id标签是主键 name是本类中主键对应的属性 column是数据库表中主键对应的那一列 -->        <id name="id" column="sid"></id>    <!--除了主键的其它属性都用property标签配置 name是本类中对应的属性 column是数据库表中对应的那一列 -->        <property name="name"></property>    </class></hibernate-mapping>

5.4 把Student.hbm.xml配置文件加到hibernate.cfg.xml中,也就是上述hibernate.cfg.xml文件代码中
<mapping resource="com/Student.hbm.xml" />这一项
5.5 创建个类,比如是com.HibernateUtils.java ,就是为了获取SessionFactory,免得一直获取SessionFactory。

package com;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;public class HibernateUtils {    private static SessionFactory sessionFactory;    private static ServiceRegistry serviceRegistry;    public static SessionFactory getSessionFactory() {        Configuration configuration = new Configuration();        configuration.configure();        serviceRegistry = new ServiceRegistryBuilder().applySettings(                configuration.getProperties()).buildServiceRegistry();        sessionFactory = configuration.buildSessionFactory(serviceRegistry);        return sessionFactory;    }}

5.6 再创建个类用来实现增删改查操作,比如名字叫com.HibernateTest_1.java 代码如下

package com;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.junit.Test;public class HibernateTest_1 {    // 获取学生    @Test    public void testAnnocationGetStudent() {        SessionFactory factory = HibernateUtils.getSessionFactory();        Session session = factory.openSession();        Transaction transaction = session.beginTransaction();        try {        // 查询主键为1的学生            Student student = (Student) session.get(Student.class, 1);            System.out.println(student);            transaction.commit();        } catch (Exception e) {            e.printStackTrace();            transaction.rollback();        }    }    // 添加学生    @Test    public void testAnnocationSaveStudent() {        SessionFactory factory = HibernateUtils.getSessionFactory();        Session session = factory.openSession();        Transaction transaction = session.beginTransaction();        try {            Student student = new Student(10, "小明");            session.save(student);            transaction.commit();        } catch (Exception e) {            e.printStackTrace();            transaction.rollback();        }    }    // 删除学生    @Test    public void testAnnocationRemoveStudent() {        SessionFactory factory = HibernateUtils.getSessionFactory();        Session session = factory.openSession();        Transaction transaction = session.beginTransaction();        try {        // 先获取删除哪个学生 再删除            Student student = (Student) session.get(Student.class, 20);            session.delete(student);            transaction.commit();        } catch (Exception e) {            e.printStackTrace();            transaction.rollback();        }    }    // 修改学生    @Test    public void testAnnocationModifyStudent() {        SessionFactory factory = HibernateUtils.getSessionFactory();        Session session = factory.openSession();        Transaction transaction = session.beginTransaction();        try {            Student student = (Student) session.get(Student.class, 1);            student.setName("小华");            session.update(student);            transaction.commit();        } catch (Exception e) {            e.printStackTrace();            transaction.rollback();        }    }}
原创粉丝点击