• 关于hibernate的一点心得


    1.部门和员工的关系:

    部门<->员工是一对多的关系,即一个部门有多个员工,所以员工表里有部门id:depart_id

    在下面这个代码中各添加部门和员工的一个记录即:新增一个部门,同时这个部门下有一个员工

    static Department add() {
    Session s = null;
    Transaction tx = null;
    try {
    Department depart = new Department();
    depart.setName("depart name");

    Employee emp = new Employee();
    emp.setDepart(depart);// 对象模型,建立两个对象之间的关联
    emp.setName("emp name");

    s = HibernateUtil.getSession();
    tx = s.beginTransaction();
    s.save(depart);//********************
    s.save(emp);//*******************
    tx.commit();
    return depart;
    } finally {
    if (s != null) {
    s.close();
    }
    }
    }

    注意:打*********号的两行顺序不变的话,控制台输出结果为:

    Hibernate: insert into Department (name) values (?)
    Hibernate: insert into Employee (name, depart_id) values (?, ?)

    如果改变的话为:

    Hibernate: insert into Employee (name, depart_id) values (?, ?)
    Hibernate: insert into Department (name) values (?)
    Hibernate: update Employee set name=?, depart_id=? where id=?

    注意区别。。。。

    2 .关于try catch finally 之间的那点事

    碰到需要返回值的,如果没有catch,只有finally的话只需在try中return下就行了,不会报错

    static Employee query(int empId) {
    Session s = null;
    Transaction tx = null;
    try {
    s = HibernateUtil.getSession();
    tx = s.beginTransaction();
    Employee emp = (Employee) s.get(Employee.class, empId);
    tx.commit();
    return emp;

    } finally {
    if (s != null) {
    s.close();
    }
    }
    }

    如果有catch那么就需要在finally之后return,不然报错

    static Employee query(int empId) {
    Session s = null;
    Transaction tx = null;
    try {
    s = HibernateUtil.getSession();
    tx = s.beginTransaction();
    Employee emp = (Employee) s.get(Employee.class, empId);
    tx.commit();
    return emp;

    }

    } catch (HibernateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

    }finally {
    if (s != null) {
    s.close();
    }
    }

    return null;
    }

  • 相关阅读:
    杭州西湖、苏州园林
    新加坡
    泰国
    旅游常用英语语句
    React 脚手架支持Typescript和Sass
    用 Scoop 管理你的 Windows 软件
    Asp.Net Core WebAPI+PostgreSQL部署在Docker中
    Ionic 4 核心概念
    Ionic Framework 4 介绍
    Google Flutter框架:使用VS Code进行开发
  • 原文地址:https://www.cnblogs.com/burns/p/3863075.html
Copyright © 2020-2023  润新知