Hibernate CURD(增删改查)单例创建SessionFactory对象

一、配置环境

这里不说怎么配置了,请看我的另一篇博客 《Hibernate配置及问题》

二、程序代码

Mysql数据库:

DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `title` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

INSERT INTO `teacher` VALUES ('1', '沈雪冰', '叫兽');
INSERT INTO `teacher` VALUES ('2', '张三', '秘书');
INSERT INTO `teacher` VALUES ('3', '马世斌', '老师');
INSERT INTO `teacher` VALUES ('4', '王八蛋', '主任');
INSERT INTO `teacher` VALUES ('5', '李三妹', '行政人员');

注意:

我刚开始手动建表设置了id主键为主键,但是没设置自增,在添加数据的时候会报错,改成自增后就没有问题了。
在配置文件也能更改此错误,例如:
native 生成器:依据底层数据库对自动生成标识符的支持能力, 来选择使用 identity, sequence 等OID生成器.
Hibernate CURD(增删改查)单例创建SessionFactory对象_第1张图片
有很多种方法,这里不给大家列举了,大家可以查看相关API文档。

Teacher.java

package com.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;


public class Teacher {
    private int id;
     private String name;
     private String title;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    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;
    }


}

Teacher.hbm.xml



    <hibernate-mapping>

    <class name="com.pojo.Teacher" table="teacher">
    <id name="id" type="integer">
       <generator class="native">generator>
    id>
    <property name="name"/>
    <property name="title" />

    class>
    hibernate-mapping>

hibernate.cfg.xml



<hibernate-configuration>
    <session-factory>
        
        <property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
        <property name="connection.url">jdbc:mysql://localhost:3306/student??useUnicode=true&characterEncoding=utf-8property>
        <property name="connection.username">rootproperty>
        <property name="connection.password">950420property>
        
        <property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
        
        <property name="hibernate.show_sql">trueproperty>

        <mapping resource="com/pojo/Teacher.hbm.xml" /> 
    session-factory>
hibernate-configuration>

单例创建 sessionFactory

SessionFactoryUtil.java

package com.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.pojo.Teacher;
public class SessionFactoryUtil {
    //单例模式
    private static SessionFactory sessionFactory=null;
    private SessionFactoryUtil(){

    }
    public static SessionFactory getSessionFactory(){
        if(sessionFactory==null)
        {
            //如果还没创建就创建一个新的对象
            Configuration configuration=new Configuration();
            configuration.configure();
            configuration.addClass(Teacher.class);
            sessionFactory=configuration.buildSessionFactory();
        }
        return sessionFactory;
    }

}

测试代码:

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.pojo.Teacher;
import com.util.SessionFactoryUtil;

public class crudTeacherDemo {

    public static void main(String[] args) {
        crudTeacherDemo test=new crudTeacherDemo();
           test.addTeacher(); //增
           test.findTeacherByid(); //查一个
           test.findAllTeacher(); //查询所有
           test.updateTeacherByid(); //更新
           test.deleteTeacher();//删除

    }
    public void findTeacherByid(){
        //根据id查找信息
        SessionFactory sessionFactory=SessionFactoryUtil.getSessionFactory(); //单例模式创建sessionfatory
        Session session=sessionFactory.openSession(); //创建session对象
        Transaction transaction=session.beginTransaction();//开始事务
        Teacher teacher=session.get(Teacher.class,1); //根据id查找信息
        System.out.println("根据id查找结果:");
        System.out.println(teacher.getName()+" "+teacher.getTitle());
        transaction.commit();//提交事务
        session.close(); //关闭session,释放资源
    }
    public void findAllTeacher(){
        SessionFactory sessionFactory=SessionFactoryUtil.getSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction transaction=session.beginTransaction();//开始事务
        Query query=session.createQuery("from Teacher");//获取查询对象,参数为hql语言,Teacher为类名
        List list=query.list();//使用查询对象返回集合,集合中封装hql中查询的类实例化对象
        System.out.println("全部信息:");
        for (int i = 0; i < list.size(); i++) {
            Teacher teacher=(Teacher) list.get(i);
            System.out.println(teacher.getName()+" "+teacher.getTitle());
        }
        transaction.commit();//关闭事务
        session.close(); //关闭session
    }
    public void updateTeacherByid(){

        SessionFactory sessionFactory=SessionFactoryUtil.getSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction transaction=session.beginTransaction();//开启事务
        Teacher teacher=session.get(Teacher.class, 1); //查找相关id的对象
        teacher.setName("沈雪冰");
        teacher.setTitle("叫兽");
        session.update(teacher); //更新信息
        transaction.commit(); //提交事务
        session.close();//关闭session
    }

    public void deleteTeacher(){
        SessionFactory sessionFactory=SessionFactoryUtil.getSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction transaction =session.beginTransaction();//开启事务
        Teacher teacher=new Teacher();
        teacher.setId(2);
        teacher=session.get(Teacher.class, 2);
        if(teacher!=null) //删除空对象会异常
        {
            session.delete(teacher);
        }
        else
        {
            System.out.println("已经删除了~!");
        }

        transaction.commit();//事务提交,相当于conn.commit
        session.close();//关闭session,释放资源
   }
    public void addTeacher(){
        SessionFactory sessionFactor=SessionFactoryUtil.getSessionFactory();
        Session session=sessionFactor.openSession();
        Transaction transaction=session.beginTransaction();
        Teacher teacher=new Teacher();
        teacher.setName("李三妹");
        teacher.setTitle("行政人员");
        session.save(teacher);
        transaction.commit();
        session.close();

    }


}

三、运行结果

Hibernate CURD(增删改查)单例创建SessionFactory对象_第2张图片

你可能感兴趣的:(Hibernate CURD(增删改查)单例创建SessionFactory对象)