欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate4学习之配置版和注解版的增删改查以及HibernateUtil类的封装(二)

程序员文章站 2022-04-14 10:40:45
...

一、hibernate4配置版增删改查。

  1. 新建HibernateUtil类,封装SessionFactory。
package com.newbeedaly.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static final SessionFactory sessionFactory=buildSessionFactory();

    private static SessionFactory buildSessionFactory(){
        Configuration configuration=new Configuration().configure(); // 实例化配置文件
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // 实例化服务登记
        return configuration.buildSessionFactory(serviceRegistry); // 获取Session工厂
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
}

2.配置hibernate.cfg.xml文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!--数据库连接设置 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>


        <!-- 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- 控制台显示SQL -->
        <property name="show_sql">true</property>

        <!-- 自动更新表结构 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 配置文件版 -->
        <mapping resource="com/newbeedaly/model/Student.hbm.xml"/>
        <!-- 注解版 -->
        <mapping class="com.newbeedaly.model.Teacher"/>
    </session-factory>

</hibernate-configuration>

3.编写Student配置文件,Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.newbeedaly.model">

    <class name="Student" table="t_student">
        <id name="id" column="stuId">
            <generator class="native"></generator>
        </id>

        <property name="name"></property>
    </class>

</hibernate-mapping>

4.编写Student类

package com.newbeedaly.model;

public class Student {

    private long id;
    private String name;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }


}

5.编写Student增删改查测试类

package com.newbeedaly.service;

import java.util.List;

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

import com.newbeedaly.model.Student;
import com.newbeedaly.util.HibernateUtil;

public class StudentTest {

    private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();

    private void add(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        Student s=new Student();
        s.setName("张三");
        session.save(s);

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    private void delete(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        Student student=(Student)session.get(Student.class, Long.valueOf(1));
        session.delete(student);

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    private void update(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        Student student=(Student)session.get(Student.class, Long.valueOf(2));
        student.setName("张三2");
        session.save(student);

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    private void getAllStudent(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        String hql="from Student";
        Query query=session.createQuery(hql);
        List<Student> studentList=query.list();
        for(Student student:studentList){
            System.out.println(student);
        }

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    public static void main(String[] args) {
        StudentTest studentTest=new StudentTest();
        // studentTest.add();
        // studentTest.delete();
        // studentTest.update();
        studentTest.getAllStudent();
    }
}

二、hibernate4注解版增删改查。

1.编写Teacher类,使用注解。

package com.newbeedaly.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="t_teacher")
public class Teacher {

    private long id;
    private String name;

    @Id
    @GeneratedValue(generator="_native")
    @GenericGenerator(name="_native",strategy="native")
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Teacher [id=" + id + ", name=" + name + "]";
    }


}

2.编写Teacher测试类

package com.newbeedaly.service;

import java.util.List;

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

import com.newbeedaly.model.Teacher;
import com.newbeedaly.util.HibernateUtil;

public class TeacherTest {

    private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();

    public void add(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        Teacher s=new Teacher();
        s.setName("张三");
        session.save(s);

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    public void delete(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        Teacher Teacher=(Teacher)session.get(Teacher.class, Long.valueOf(1));
        session.delete(Teacher);

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    public void update(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        Teacher Teacher=(Teacher)session.get(Teacher.class, Long.valueOf(2));
        Teacher.setName("张三2");
        session.save(Teacher);

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    public void getAllTeacher(){
        Session session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务

        String hql="from Teacher";
        Query query=session.createQuery(hql);
        List<Teacher> TeacherList=query.list();
        for(Teacher Teacher:TeacherList){
            System.out.println(Teacher);
        }

        session.getTransaction().commit(); // 提交事务
        session.close(); // 关闭session
    }

    public static void main(String[] args) {
        TeacherTest TeacherTest=new TeacherTest();
        // TeacherTest.add();
        // TeacherTest.delete();
        // TeacherTest.update();
        TeacherTest.getAllTeacher();
    }
}

运行测试类测试。

相关标签: hibernate4