超详细的hibernate实现对MySQL的CRUD

超详细的hibernate实现对MySQL的CRUD

文章目录

    • 超详细的hibernate实现对MySQL的CRUD
  • 前言
  • 一、操作前的准备
    • 1.创建maven项目
    • 2.导入maven依赖
    • 3.创建实体类
    • 4.配置数据库
    • 5.实体类和数据库的映射
    • 6.创建hibernateUtil工具类
  • 二.对MySQL的数据查询
    • 1.使用get和load按下标索引实现数据的查询
    • 2.使用createQuery查询
    • 3.使用Criteria查询
    • 4.多表查询
        • 4.1 one-many(双向一对多)
        • 4.2 many-one(单向多对一)
        • 4.3 one-many(单向一对多)
        • 4.4 one-one(单向一对一)
        • 4.5 one-one(双向一对一)
  • 三、对MySQL的数据增加
  • 四、对MySQL的数据删除
  • 五、对MySQL的数据修改
  • 总结


前言

使用hibernate技术实现对MySQL数据库的crud

一、操作前的准备

1.创建maven项目

不会的建议自行百度如何创建一个maven项目,这里不做过多解释。

2.导入maven依赖

在pom.xml配置文件中
<dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-coreartifactId>
            <version>4.3.11.Finalversion>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.41version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
            <scope>providedscope>
        dependency>
    dependencies>

3.创建实体类

根据你的数据库表的字段来创建对应的实体类,我这里以学生表为例

数据库为:超详细的hibernate实现对MySQL的CRUD_第1张图片
超详细的hibernate实现对MySQL的CRUD_第2张图片

创建的与之对应的实体类为:

tip:我这里用了lombok的注解,自动get,set,想了解可以去百度一下,挺好用的。

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/25 10:25
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "student")
public class Student {
     
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "source")
    private Integer source;
}

4.配置数据库

tip:这一步是整个操作过程的核心,务必注意,关于这个文件的位置,很多人说放在src目录下,因为加载程序默认是加载这个位置下的配置文件,但是我试过不放在此处用全路径名去加载依然可以使用。 在src目录下创建hibernate.cfg.xml文件



<hibernate-configuration>

    <session-factory>
        
        <property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTCproperty>
        <property name="connection.username">rootproperty>
        <property name="connection.password">123456property>

        
        
        <property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
        
        <property name="current_session_context_class">threadproperty>
        
        <property name="show_sql">trueproperty>
        
        <property name="hbm2ddl.auto">updateproperty>
        
        <mapping resource="mapper/Student.hb.xml" />
    session-factory>

hibernate-configuration>

5.实体类和数据库的映射

这一步也很关键,如果说上面哪一步决定你能不能访问数据库,那这一步决定你能不能从数据库中取出数据到java程序中。 创建实体类名.hbn.xml文件:




<hibernate-mapping package="entity">
    
    <class name="Student" table="student">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="name" column="name"/>
        <property name="source" column="source"/>
    class>

hibernate-mapping>

6.创建hibernateUtil工具类

每一次对数据库的操作都需要创建SessionFactory,获取Session,关闭Session和SessionFactory这些操作,创建工具类为了简化这些操作。
package util;

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

/**
 * @author :LSS
 * @description: hibernate获取Session的工具类
 * @date :2020/12/25 10:06
 */
public class HibernateUtil {
     

    //声明全局SessionFactory对象
    public static final SessionFactory sessionFactory;
    // 存放Session使用ThreadLocal,它可以隔离多个线程的数据共享,省去对线程同步
    public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

    //静态代码块创建sessionFactory
    static
    {
     
        try
        {
     
            // 采用默认的hibernate.cfg.xml来启动一个Configuration的实例
            Configuration cfg = new Configuration().configure();
            // 以Configuration实例来创建SessionFactory实例
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex)
        {
     
            System.err.println("创建SessionFactory失败>>>" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    //创建Session
    public static Session GetSession() throws HibernateException
    {
     
        //通过线程对象.get()方法安全创建Session
        Session s = session.get();
        // 如果该线程还没有Session,则创建一个新的Session
        if (s == null)
        {
     
            s = sessionFactory.openSession();
            // 将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }

    //关闭Session
    public static void CloseSession() throws HibernateException
    {
     
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}
至此,已经完成了增删改查之前的所有配置操作,下面上正题,CRUD。

二.对MySQL的数据查询

1.使用get和load按下标索引实现数据的查询

这种方式是按id的值来查询的,关于get和load方法的区别,请自行百度,这里不做过多解释。
import entity.Student;
import org.hibernate.Session;
import org.junit.Test;
import util.HibernateUtil;

/**
 * @author :LSS
 * @description: hibernate的数据查询
 * @date :2020/12/25 10:08
 */
public class TestBasic {
     

    @Test
    public void test() {
     
        //获取Session
        Session session = HibernateUtil.GetSession();
        //开启事务
        session.beginTransaction();

        //get查询方式
        Student student = (Student) session.get(Student.class, 2);
        System.out.println("student = " + student);
        //load查询方式
        Student load = (Student) session.load(Student.class, 3);
        System.out.println("load = " + load);

        //事务提交
        session.getTransaction().commit();
        //关闭事务,SessionFactory
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }
}

2.使用createQuery查询

此种方式相对于第一种更加的实用,其支持hql语句,下面的例子中一共包含六种查询方式:条件查询,模糊查询,排序查询,分页查询,投影查询,聚合查询。

import com.alibaba.fastjson.JSON;
import entity.Student;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import util.HibernateUtil;

import java.util.List;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/28 10:09
 */
public class TestSelect {
     

    @Test
    public void Select() {
     
        //获取Session对象,保存在ThreadLocal中
        Session session = HibernateUtil.GetSession();

        //创建查询Query(条件查询)
//        String hql = "from Student where name = ? and source = ?";
//        Query query = session.createQuery(hql);
        //创建查询Query(模糊查询)
//        Query query = session.createQuery("from Student where name like ?");
        //创建查询Query(排序查询)默认是asc升序,desc是降序
//        Query query = session.createQuery("from Student order by id asc");
//        Query query = session.createQuery("from Student order by id desc");
        //创建查询Query(分页查询)
//        Query query = session.createQuery("from Student");
        //创建查询Query(投影查询)
//        Query query = session.createQuery("select name from Student");
        Query query = session.createQuery("select name,source from Student");
        //创建查询Query(聚合查询)
//        Query query = session.createQuery("select sum(source) from Student group by name");

        //开启事务
        Transaction transaction = session.beginTransaction();

        //设置参数,从0开始(条件查询)
//        query.setParameter(0,"小庄");
//        query.setParameter(1,150);
        //设置参数,从0开始(模糊查询)
//        query.setParameter(0,"__");
        //设置参数,从0开始(分页查询)
        query.setFirstResult(1);  //设置开始行数,从0开始
        query.setMaxResults(2);  //设置每页容量

        //执行查询(条件查询,模糊查询,排序查询,分页查询)
//        List list = query.list();
        //执行查询(投影查询)
        List<Object[]> list = query.list();
        //执行查询(聚合查询)
//        List list = query.list();
        System.out.println(list.size());

        //遍历取值(聚合查询)
//        for (Long stu:list) {
     
//            System.out.println(stu);
//        }
        //遍历取值(投影查询)
        for (int i = 0; i < list.size(); i++) {
     
            for (Object stu : list.get(i)) {
     
                System.out.println(JSON.toJSONString(stu));
            }
        }
        //遍历取值(条件查询,模糊查询,排序查询,分页查询)
//        for (int i = 0 ; i < list.size(); i++){
     
//            System.out.println(JSON.toJSONString(list.get(i)));
//        }
        //提交事务
        transaction.commit();
        //关闭资源
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

}

3.使用Criteria查询

这种方式相对于createQuery来说,不需要创建hql语句
import entity.Student;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import util.HibernateUtil;

import java.util.List;

/**
 * @author :LSS
 * @description: 使用Criteria对象查询结果
 * @date :2020/12/28 16:22
 */
public class TestCriteria {
     

    /**
     * 查询所有
     */
    @Test
    public void test1() {
     
        Session session = HibernateUtil.GetSession();
        Criteria criteria = session.createCriteria(Student.class);
        Transaction transaction = session.beginTransaction();
        List<Student> list = criteria.list();
        for (Student stu : list
        ) {
     
            System.out.println("stu = " + stu);
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

    /**
     * 条件查询
     */
    @Test
    public void test2() {
     
        //获取Session
        Session session = HibernateUtil.GetSession();
        //创建Criteria对象
        Criteria criteria = session.createCriteria(Student.class);
        //设置查询条件
        criteria.add(Restrictions.eq("name", "小庄"));
        criteria.add(Restrictions.eq("source", 150));
        //开启事务
        Transaction transaction = session.beginTransaction();
        //执行查询语句,返回查询结果
        List<Student> list = criteria.list();
        //遍历打印结果
        for (Student stu : list
        ) {
     
            System.out.println("stu = " + stu);
        }
        //提交事务
        transaction.commit();
        //关闭资源
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

    /**
     * 模糊查询
     */
    @Test
    public void test3() {
     
        Session session = HibernateUtil.GetSession();
        Criteria criteria = session.createCriteria(Student.class);
        criteria.add(Restrictions.like("name", "小_"));
        Transaction transaction = session.beginTransaction();
        List<Student> list = criteria.list();
        for (Student stu : list
        ) {
     
            System.out.println("stu = " + stu);
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

    /**
     * 排序查询
     */
    @Test
    public void test4() {
     
        Session session = HibernateUtil.GetSession();
        Criteria criteria = session.createCriteria(Student.class);
        //降序排列
//        criteria.addOrder(Order.desc("id"));
        //默认升序排列
        criteria.addOrder(Order.asc("id"));
        Transaction transaction = session.beginTransaction();
        List<Student> list = criteria.list();
        for (Student stu : list
        ) {
     
            System.out.println("stu = " + stu);
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

    /**
     * 分页查询
     */
    @Test
    public void test5() {
     
        Session session = HibernateUtil.GetSession();
        Criteria criteria = session.createCriteria(Student.class);
        //设置查询起始行
        criteria.setFirstResult(2);
        //设置页容量
        criteria.setMaxResults(2);
        Transaction transaction = session.beginTransaction();
        List<Student> list = criteria.list();
        for (Student stu : list
        ) {
     
            System.out.println("stu = " + stu);
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

    /**
     * 聚合查询
     */
    @Test
    public void test6() {
     
        //获取Session
        Session session = HibernateUtil.GetSession();
        //创建Criteria对象
        Criteria criteria = session.createCriteria(Student.class);
        //这里使用Projections.projectionList来聚集多个聚合查询
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.rowCount());
        projectionList.add(Projections.sum("source"));
        criteria.setProjection(projectionList);
        //开启事务
        Transaction transaction = session.beginTransaction();
        //执行查询,返回结果为一个数组,里面装的数几个聚合的结果组合
        List list = criteria.list();
        //遍历打印,因为就一条数据,这里直接用哪个get[0]来操作了
        Object[] arr = (Object[])list.get(0);
        for(Object ob : arr){
     
            System.out.println(ob.toString());
        }
        //提交事务
        transaction.commit();
        //关闭资源
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }
}

4.多表查询

以上查询都是在单表中进行的查询,此处的查询涉及到两张及以上表的查询;
关于多表查询,涉及到数据库表之间的关系,以及实体类中彼此之间的关系,最后还有配置文件中的映射关系(相对来说比较复杂)
在此说明一下,这个东西分为单向和多向,所谓单向就是(拿A和B举例)A只能查B,或者B只能查A,所谓双向就是A可以查B,同时B也可以查A。

4.1 one-many(双向一对多)

在“多”的实体类中引入“少”的类属性,在“少”的实体类中引入多的Set集合,具体看下面实体类。 对于双向一对多和多对一,我这里把他默认为统一处理方式,如果有错的地方还希望大牛及时指正,在此谢过。

订单表:其中PRI为主键,MUL为外键
超详细的hibernate实现对MySQL的CRUD_第3张图片
超详细的hibernate实现对MySQL的CRUD_第4张图片
顾客表:
超详细的hibernate实现对MySQL的CRUD_第5张图片
超详细的hibernate实现对MySQL的CRUD_第6张图片
订单表实体类:

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description: 订单表实体类
 * @date :2020/12/29 10:24
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
     
    private Long id;
    private String orderno;
    private String productName;

    //关联客户表
    private Customer customer;

    @Override
    public String toString() {
     
        return "Order{" +
                "id=" + id +
                ", orderno='" + orderno + '\'' +
                ", productName='" + productName + '\'' +
                '}';
    }
}

客户表实体类:

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashSet;
import java.util.Set;

/**
 * @author :LSS
 * @description: 客户表实体类
 * @date :2020/12/29 10:25
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Customer {
     
    private Long id;
    private String name;
    private String gender;
    private Integer age;
    private String level;

    //关联订单表
    private Set<Order> orders = new HashSet<Order>();

    @Override
    public String toString() {
     
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", level='" + level + '\'' +
                '}';
    }
}

订单表和订单实体类的映射配置文件:





<hibernate-mapping package="entity">
    
    <class name="Order" table="t_order">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="orderno" column="orderno"/>
        <property name="productName" column="product_name"/>

        
        <many-to-one name="customer" class="entity.Customer" column="c_id">many-to-one>
    class>

hibernate-mapping>

客户表和客户实体类的映射配置文件:





<hibernate-mapping package="entity">
    
    <class name="Customer" table="customer">
        
        <id name="id" column="c_id">
            
            <generator class="native">generator>
        id>
        
        <property name="name" column="c_name"/>
        <property name="gender" column="c_gender"/>
        <property name="age" column="c_age"/>
        <property name="level" column="c_level"/>

        
        <set name="orders"> 
            <key column="c_id">key> 
            <one-to-many class="Order">one-to-many> 
        set>
    class>

hibernate-mapping>

测试类:

	/**
     * 内连接
     */
    @Test
    public void test1(){
     
        Session session = HibernateUtil.GetSession();
        //内连接
		//Query query = session.createQuery("select c.name,o.productName from Customer c join c.orders o where c.id = o.customer.id");
        //左外连接
		//Query query = session.createQuery("select c.name,o.productName from Customer c left join c.orders o where c.id = o.customer.id");
        //右外连接
        Query query = session.createQuery("select c.name,o.productName from Customer c right join c.orders o where c.id = o.customer.id");
        Transaction transaction = session.beginTransaction();
        List list = query.list();
        for (Object obj:list
             ) {
     
            System.out.println(JSON.toJSONString(obj));
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

4.2 many-one(单向多对一)

对于单向多对一,“多"的一方实体类中引入少的一方做属性,在“多”的一方配置文件中使用many-to-one进行关系的映射。具体看实例:

Gun类(枪类):

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


/**
 * @author :LSS
 * @description:
 * @date :2020/12/29 15:58
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Gun {
     
    private int id;
    private String type;

    @Override
    public String toString() {
     
        return "Gun{" +
                "id=" + id +
                ", type='" + type + '\'' +
                '}';
    }
}

Bullte类(子弹类)

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/29 16:00
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bullte {
     
    private int id;
    private String caliber;
    private String weight;
    private int gun_id;

    private Gun gun;
}

Gun.hbn.xml(枪的映射配置文件类)





<hibernate-mapping package="entity">
    
    <class name="Gun" table="gun">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="type" column="type"/>
    class>
hibernate-mapping>

Bullte.hbn.xml(子弹的映射配置文件)





<hibernate-mapping package="entity">
    
    <class name="Bullte" table="bullte">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="caliber" column="caliber"/>
        <property name="weight" column="weight"/>
        <property name="gun_id" column="gun_id"/>

        
        <many-to-one name="gun" class="Gun">many-to-one>
    class>
hibernate-mapping>

Test(测试类)

import com.alibaba.fastjson.JSON;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import util.HibernateUtil;

import java.util.List;

/**
 * @author :LSS
 * @description: 测试单向一对多
 * @date :2020/12/29 16:07
 */
public class Onetomany {
     
    @Test
    public void test1(){
     
        Session session = HibernateUtil.GetSession();
        Query query = session.createQuery("from Bullte b left join b.gun g where b.gun_id = g.id");
        Transaction transaction = session.beginTransaction();
        List list = query.list();
        System.out.println(list.size());
        for (Object obj:list
             ) {
     
            System.out.println("obj = " + JSON.toJSONString(obj));
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }
}

4.3 one-many(单向一对多)

单向一对多,在少的一方实体类中存放多的一方的实体类的Set集合,在少的一方的映射配置文件中使用set进行配置,具体看下面实例:

Gun(枪类)

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashSet;
import java.util.Set;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/29 15:58
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Gun {
     
    private int id;
    private String type;
    private Set<Bullte> bulltes = new HashSet<Bullte>();

    public Gun(int id, String type) {
     
        this.id = id;
        this.type = type;
    }

    @Override
    public String toString() {
     
        return "Gun{" +
                "id=" + id +
                ", type='" + type + '\'' +
                '}';
    }
}

Bullte(子弹类)

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/29 16:00
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bullte {
     
    private int id;
    private String caliber;
    private String weight;
    private int gun_id;
}

Gun.hbn.xml(枪类的映射配置文件)





<hibernate-mapping package="entity">
    
    <class name="Gun" table="gun">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="type" column="type"/>
        
        <set name="bulltes">
            <key column="gun_id">key> 
            <one-to-many class="Bullte">one-to-many>
        set>
    class>
hibernate-mapping>

Buttle.hbn.xml(子弹类的映射配置文件类)





<hibernate-mapping package="entity">
    
    <class name="Bullte" table="bullte">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="caliber" column="caliber"/>
        <property name="weight" column="weight"/>
        <property name="gun_id" column="gun_id"/>
    class>
hibernate-mapping>

test测试类

import com.alibaba.fastjson.JSON;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import util.HibernateUtil;

import java.util.List;

/**
 * @author :LSS
 * @description: 测试单向一对多
 * @date :2020/12/29 16:07
 */
public class Onetomany {
     
    @Test
    public void test1(){
     
        Session session = HibernateUtil.GetSession();
        Query query = session.createQuery("from Gun g left join g.bulltes b where g.id = b.gun_id");
        Transaction transaction = session.beginTransaction();
        List list = query.list();
        System.out.println(list.size());
        for (Object obj:list
             ) {
     
            System.out.println("obj = " + JSON.toJSONString(obj));
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }
}

4.4 one-one(单向一对一)

对于单向一对一,(拿A和B举例),在A表中设置B类当属性,在A的映射配置文件中进行one-to-one的关系映射,具体看实例:
Person实体类:

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description: 单向一对一的前“一”
 * @date :2020/12/29 17:06
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
     
    private Integer id;
    private String name;
    private String sex;

    private Card card;
}

Card实体类:

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description: 单向一对一的后“一”
 * @date :2020/12/29 17:06
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Card {
     
    private Integer id;
    private String cardNo;
}

Person.hbn.xml映射配置文件:





<hibernate-mapping package="entity">
    
    <class name="Person" table="person">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="name" column="name"/>
        <property name="sex" column="sex"/>
        
        <one-to-one name="card" class="Card">one-to-one>
    class>
hibernate-mapping>

Card.hbn.xml映射配置文件:





<hibernate-mapping package="entity">
    
    <class name="Card" table="card">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="cardNo" column="card_no"/>

    class>
hibernate-mapping>

Test测试类:

import com.alibaba.fastjson.JSON;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import util.HibernateUtil;

import java.util.List;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/29 17:13
 */
public class Onetoone {
     

    @Test
    public void test1(){
     
        Session session = HibernateUtil.GetSession();
        Query query = session.createQuery("from Person p left join p.card");
        Transaction transaction = session.beginTransaction();
        List list = query.list();
        System.out.println(list.size());
        for (Object obj :
                list) {
     
            System.out.println("obj = " + JSON.toJSONString(obj));
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }
}

4.5 one-one(双向一对一)

对于双向一对一,在A表和B表中分别设置对方类当做属性,在各自的映射配置文件中使用one-to-one进行映射配置,具体看以下实例:
Person实体类:

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description: 单向一对一的前“一”
 * @date :2020/12/29 17:06
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
     
    private Integer id;
    private String name;
    private String sex;

    private Card card;
}

Card实体类:

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author :LSS
 * @description: 单向一对一的后“一”
 * @date :2020/12/29 17:06
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Card {
     
    private Integer id;
    private String cardNo;

    private Person person;
}

Person.hbn.xml映射配置文件:





<hibernate-mapping package="entity">
    
    <class name="Person" table="person">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="name" column="name"/>
        <property name="sex" column="sex"/>

        
        <one-to-one name="card" class="Card">one-to-one>
    class>
hibernate-mapping>

Card.hbn.xml映射配置文件:





<hibernate-mapping package="entity">
    
    <class name="Card" table="card">
        
        <id name="id" column="id">
            
            <generator class="native">generator>
        id>
        
        <property name="cardNo" column="card_no"/>
        
        <one-to-one name="person" class="Person">one-to-one>
    class>
hibernate-mapping>

Test测试类:

import com.alibaba.fastjson.JSON;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import util.HibernateUtil;

import java.util.List;

/**
 * @author :LSS
 * @description:
 * @date :2020/12/29 17:13
 */
public class Onetoone {
     

    @Test
    public void test1(){
     
        Session session = HibernateUtil.GetSession();
        Query query = session.createQuery("from Card c left join c.person");
        Transaction transaction = session.beginTransaction();
        List list = query.list();
        System.out.println(list.size());
        for (Object obj :
                list) {
     
            System.out.println("obj = " + JSON.toJSONString(obj));
        }
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }
}


三、对MySQL的数据增加

对于数据库增加数据的方法有两个save()和saveOrUpdate(),这两个方法的区别是,save()方法用于确认要添加的数据,另一个用于对于不确定要添加数据时,交给hibernate去自行判断是添加还是更新数据,具体例子看以下实例:
@Test
    public void testsave(){
     
        Session session = HibernateUtil.GetSession();
        Transaction transaction = session.beginTransaction();
        //插入数据
        Student xz = new Student("小庄", 150);
        Student student2 = new Student("赤练",145);
        session.save(xz);
        session.saveOrUpdate(student2);
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

四、对MySQL的数据删除

数据库的删除使用delete()方法,具体看实例:
@Test
    public void testDelete(){
     
        Session session = HibernateUtil.GetSession();
        Transaction transaction = session.beginTransaction();
        //删除数据
        Object o = session.get(Student.class, 4);
        session.delete(o);
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

五、对MySQL的数据修改

对于mysql数据的修改这是其中一种方法:
@Test
    public void testDelete(){
     
        Session session = HibernateUtil.GetSession();
        Transaction transaction = session.beginTransaction();
        Student o = (Student) session.get(Student.class, 2);
        //更改数据
        o.setName("小黑");
        session.update(o);
        transaction.commit();
        HibernateUtil.CloseSession();
        HibernateUtil.sessionFactory.close();
    }

总结

前前后后辛苦了两个周,算是对hibernate有了个基本的认识,还有个多对多的关系,后续更新,敬请关注,如果有写的不对的地方,还请指正。本人活跃论坛哦。

你可能感兴趣的:(hibernate,hibernate,java,mysql,数据库,sql)