利用Hibernate进行数据库的增删改查

Hibernate框架的主要作用是操纵数据库

因此其可以代替servlet中的DAO层,无需再写sql语句

因此也有对应的数据库增删改查的方法

1.添加数据

package com.oracle.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.oracle.model.Person;



public class Demo {

    public static void main(String[] args) {
        //首先实例化核心配置文件hibernate.cfg.xml
        Configuration configuration=new Configuration().configure();
        //实例化服务登记,,复制粘贴
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 
        //创建Session工厂
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); 
        Session session=sessionFactory.openSession(); //生成一个session
        session.beginTransaction(); //开启事务
        
        //先运行程序,生产数据库表
        //以下是添加数据流程
        Person person = new Person(); //首先实例化person类
        person.setRealName("张三");  //利用set方法设置值
        person.setSex("男");
     session.save(person); //session中的save方法将数据保存至数据库中 session.getTransaction().commit(); //提交事务 session.close(); //关闭session sessionFactory.close(); //关闭session工厂 } }

运行后在控制台会输出一条sql语句

 此时打开SQLyog,数据已经被添加至t_person表中

2.删除操作

 Person person=(Person)session.get(Person.class, Integer.valueOf(1)); //session的get方法,传入Person类以及主键编号
 session.delete(product);  //直接使用session的delete方法,根据主键删除某条数据

3.修改操作

Person person=(Person)session.get(Person.class, Integer.valueOf(1)); //通删除操作,需要先获取要修改的条目的主键编号
person.setRealName("李四");  //使用set方法进行修改操作
pserson.setSex("女");
session.save(person);//保存

运行程序后,控制台输首先输出一条select语句,是根据主键查找数据

然后在输出一条update语句修改数据

4.查询操作

String hql="from Person"; //创建一个hql语句,from类名
Query query=session.createQuery(hql); 利用session中的createQuery方法,让hibernate自动生成sql语句
        
@SuppressWarnings("unchecked") //压制警告
List<Person> List=query.list(); //查询出的结果用一个链表接收
for(Person person:List){   
  System.out.println(person
); //遍历链表,此时输出的是一个地址,若要输出查询出的数据,需要在Person类中重写toString方法
}

运行后,控制台输出select查询语句,并将数据打印

原文地址:https://www.cnblogs.com/wangqun1234/p/8283494.html