zoukankan      html  css  js  c++  java
  • Hibernate使用

    今天配置Hibernate配置了好久,各种改错。说实话,我并没有感觉到使用Hibernate的方便之处,至少比Django麻烦的多。

    下面总结一下今天对Hibernate的使用。

    1、下载Hibernate

    到这里http://hibernate.org/orm/releases/下载,我使用的是java 8,所有下载了5.2。下载后解压,将required文件下的jar文件加入的工程中去。

    2、配置文件之hibernate.cfg.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-configuration SYSTEM 
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <!-- Assume test is the database name -->
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost/pgv2
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1234</property>
    
        <!-- show_sql: 操作数据库时,会 向控制台打印sql语句 -->
        <property name="show_sql">true</property>
    
    
    
        <!-- format_sql: 打印sql语句前,会将sql语句先格式化 -->
        <property name="format_sql">true</property>
        <!-- 是否自动创建数据库表 他主要有一下几个值: validate:当sessionFactory创建时,自动验证或者schema定义导入数据库。 
            create:每次启动都drop掉原来的schema,创建新的。 create-drop:当sessionFactory明确关闭时,drop掉schema。 
            update(常用):如果没有schema就创建,有就更新。 -->
    
        <property name="hbm2ddl.auto">update</property>
    
        <!-- List of XML mapping files -->
        <property name="dialect"></property>
        <mapping resource="User.hbm.xml" />
        <mapping resource="onlineUser.hbm.xml" />
    
    </session-factory>
    </hibernate-configuration> 
    hibernate.cfg.xml

    这里我加了一些注释,有些一眼就可以明白的东西就没有注释了(还是没有随手注释的习惯)。一般常用的配置这样就可以了。

    我想说的是这个文件的存放位置,所有的hibernate的配置文件的存放位置,默认都在src下,我查了一些怎么修改也没有找到。真是让强迫症的我难受的很。。

                                                    

    这样就配置好了hibernate的数据库连接。

    3、实体类

    实体类要写入数据库的属性必须有setter和getter,必须有构造方法。如果是mysql数据库,必须有一个id作为主键,一般变量名也直接设置为id

    看我的User类:

    package com.PGV2.javaBean;
    
    public class User {
        private int id;
        private String userName;
        private String userPwd;
        private String role;
        private int login;
        public User( String userName, String userPwd, String role, int login) {
            this.userName = userName;
            this.userPwd = userPwd;
            this.role = role;
            this.login = login;
        }
        public User() {
            // TODO Auto-generated constructor stub
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getUserPwd() {
            return userPwd;
        }
        public void setUserPwd(String userPwd) {
            this.userPwd = userPwd;
        }
        public String getRole() {
            return role;
        }
        public void setRole(String role) {
            this.role = role;
        }
        public int isLogin() {
            return login;
        }
        public void setLogin(int login) {
            this.login = login;
        }
        
        
    }
    USer.java

    要注意的是,id是自增的,不用写在构造方法里。

    4、实体类配置文件 User.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
     "-//Hibernate/Hibernate Mapping DTD//EN"
     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
    
    <hibernate-mapping>
       <class name="com.PGV2.javaBean.User" table="user">
          <meta attribute="class-description">
             This class contains the User detail. 
          </meta>
          <id name="id" type="int" column="id">
             <generator class="native"/>
          </id>
          <property name="userName" column="username" type="string"/>
          <property name="userPwd" column="userpwd" type="string"/>
          <property name="role" column="role" type="string"/>
          <property name="login" column="login" type="int"/>
       </class>
    </hibernate-mapping>
    User.hbm.xml

    5、DAO操作 

    我把DAO操作直接封装在一个类中,这样用的时候示例化这个类就行。没有接口类,时间有限。。

    我的manageUser.java

    package com.PGV2.DAO;
    
    import java.util.List;
    
    import javax.management.Query;
    
    import java.util.Date;
    import java.util.Iterator;
    
    import org.hibernate.Criteria;
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.criterion.Restrictions;
    
    import com.PGV2.javaBean.User;
    import com.PGV2.test.Employee;
    
    public class manageUser {
        private static SessionFactory factory;
    
        public manageUser() {
            // TODO Auto-generated constructor stub
            try {
                factory = new Configuration().configure().buildSessionFactory();
            } catch (Throwable ex) {
                System.err.println("Failed to create sessionFactory object." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
    
        /*
         * 增加一个用户
         */
        public Integer addUser(User tmpUser) {
            Session session = factory.openSession();
            Transaction tx = null;
            Integer userID = null;
            try {
                tx = session.beginTransaction();
                User newUser = tmpUser;
                userID = (Integer) session.save(newUser);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
            return userID;
    
        }
    
        /*
         * 列出所有的用户
         */
        public List listUsers() {
            Session session = factory.openSession();
            Transaction tx = null;
            List users = null;
            try {
                tx = session.beginTransaction();
                users = session.createQuery("FROM User").list();
                for (Iterator iterator = users.iterator(); iterator.hasNext();) {
                    User tmpUser = (User) iterator.next();
                    System.out.println(tmpUser.getUserName());
                }
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
            return users;
        }
    
        /*
         * 更新密码
         */
        public void updateUserPwd(Integer userID, String pwd) {
            Session session = factory.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                User tmpUsere = (User) session.get(User.class, userID);
                tmpUsere.setUserPwd(pwd);
                ;
                session.update(tmpUsere);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
        }
        /*
         * 更新用户在线状态
         */
        public void updateUser(User tmpUser){
            Session session = factory.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                //User tmpUsere = (User) session.get(User.class, tmpUser.getId());
                session.update(tmpUser);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
        }
    
        /*
         * 删除一个用户
         */
        public void deleteEmployee(Integer userID) {
            Session session = factory.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                User tmpUser = (User) session.get(User.class, userID);
                session.delete(tmpUser);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
        }
    
        public User getUserById(Integer userID) {
            Session session = factory.openSession();
            Transaction tx = null;
            User tmpUser = null;
            try {
                tx = session.beginTransaction();
                tmpUser = (User) session.get(User.class, userID);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
            return tmpUser;
        }
    
        public User getUserByValid(String userName, String userPwd) {
            Session session = factory.openSession();
            Transaction tx = null;
            User tmpUser = null;
            try {
                tx = session.beginTransaction();
                org.hibernate.query.Query query = 
                        session.createQuery("from User u where u.userName = :name  and u.userPwd = :pwd")
                            .setParameter("name", userName).setParameter("pwd", userPwd);
                List res = query.list();
                if(res!=null||res.size()!=0){
                    Iterator it = res.iterator();
                    tmpUser = (User) it.next();
                }
                tx.commit();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                session.close();
            }
            return tmpUser;
        }
    
    }
    View Code

    这里要特别说明有两个对应:

    实体类配置文件的变量名要和实体类的变量名一致。

    比如说我的User.java 里有变量:userName,我的User.hbm.xml里

    <property name="userName" column="username" type="string"/>,这个对应的 name就应该是userName,至于大小写是否敏感,还没有验证。最后一致。然后column的值跟

    数据库的列名一致。我一般不建立表格,让其自己生成,不容易出错。

    第二个对应是这里:

    org.hibernate.query.Query query = 
                        session.createQuery("from User u where u.userName = :name  and u.userPwd = :pwd")
                            .setParameter("name", userName).setParameter("pwd", userPwd);

    这是我的manageUser中的一句话,使用hql查询数据库是否存在用户名和密码为我传入的两个值的记录。

    这里的hql 语句中,from User,这个User对应的User.java这个类,当然u.userName和u.userPwd对应的就是User类的两个类成员变量。

  • 相关阅读:
    gtest(C++单元测试框架)
    tinyXML入门
    笔记 解决vue3动态绑定本地图片失效问题
    面试技巧
    vuex 状态管理
    插槽的使用
    Vue-router 路由
    Vue组件
    (转)JS 常用 DOM
    9-26
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/9136491.html
Copyright © 2011-2022 走看看