zoukankan      html  css  js  c++  java
  • 关于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;
    }

  • 相关阅读:
    将博客部署到k3s中
    docker/docker swarm学习
    windows共享文件夹使用中的问题(SMB协议)
    洛谷P1280 尼克的任务 题解 动态规划/最短路
    CF1B.Spreadsheets(电子表格) 题解 模拟
    洛谷P1595 信封问题 题解 错排问题
    洛谷P1809 过河问题 经典贪心问题
    CF1238E.Keyboard Purchase 题解 状压/子集划分DP
    洛谷P2719 搞笑世界杯 题解 概率DP入门
    Treap(树堆)入门
  • 原文地址:https://www.cnblogs.com/burns/p/3863075.html
Copyright © 2011-2022 走看看