• hibernate连接数据库和使用


    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.microsoft.sqlserver.jdbc.SQLServerDriver</property>
            <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=UsersDB</property>
            <property name="connection.username">sa</property><!-- 指定数据库用户名 -->
            <property name="connection.password">1234</property><!-- 指定数据库密码 -->
            <property name="hibernate.show_sql">true</property>
            <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
            <!-- 配置映射文件 -->
            <mapping resource="com/ssh/models/Users.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

    HibernateSessionFactory.java模板

    public class HibernateSessionFactory {
        //实例化ThreadLocal类
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        //实例化Configuration类
        private  static Configuration configuration = new Configuration();  
        //声明SessionFactory接口,采用工厂模式
        private static SessionFactory sessionFactory;
        //定义configFile变量并赋值
        private static String configFile = "/hibernate.cfg.xml";
        //静态块
        static {
            try {
                //读取默认的配置文件hibernate.cfg.xml, 连接数据库
                configuration.configure(configFile);
                //实例化SessionFactory
                sessionFactory = configuration.buildSessionFactory();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        private HibernateSessionFactory() { }//创建无参的HibernateSessionFactory构造函数
        //获取Session
        public static Session getSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
            //判断是否已经存在Session对象
            if (session == null || !session.isOpen()) {
                //如果SessionFactory对象为null,则创建SessionFactory
                if (sessionFactory == null) {
                    rebuildSessionFactory();//调用rebuildSessionFactory方法创建SessionFactory
                }
                //判断SessionFactory对象是否为null,如果不是,则打开Session
                session = (sessionFactory != null) ? sessionFactory.openSession(): null;
                threadLocal.set(session);
            }
    
            return session;
        }
        //重新创建SessionFactory
        public static void rebuildSessionFactory() {
            try {
                configuration.configure(configFile);
                sessionFactory = configuration.buildSessionFactory();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //关闭Session
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
            threadLocal.set(null);
            if (session != null) {
                session.close();
            }
        }
        //SessionFactory对象的getXXX()方法
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
        //configFile属性的setXXX()方法
        public static void setConfigFile(String configFile) {
            HibernateSessionFactory.configFile = configFile;
            sessionFactory = null;
        }
        //Configuration属性的getXXX()方法
        public static Configuration getConfiguration() {
            return configuration;
        }
    }

    UsersDao.java使用HibernateSessionFactory

    public class UsersDao {
        //验证登录
        public boolean checkLogin(Users user){
            boolean flag=true;
            //得到session
            Session session=null;
            try{
                session=HibernateSessionFactory.getSession();
                //hql语句,Users代表是models里的实体类,name和password代表实体类的属性
                String queryString="from Users where name=? and password=?";
                //创建查询
                Query queryObject=session.createQuery(queryString);
                queryObject.setParameter(0, user.getName());
                queryObject.setParameter(1, user.getPassword());
                //执行查询获得的结果,list中的每一个元素代表一个Users的对象
                List list=queryObject.list();
                if(list.size()==0){
                    flag=false;//登陆不成功
                }
                return flag;
            }catch (Exception e) {
                e.printStackTrace();
                return false;
            }finally{//关闭session
                HibernateSessionFactory.closeSession();//调用HibernateSessionFactory的静态方法关闭Session
            }
        }
        //注册用户的方法
        public int registerUser(Users user){
            int num=0;//标识注册是否成功,0表示不成功,>0成功
            //得到session
            Session session=null;
            Transaction transaction=null;
            try{
                session=HibernateSessionFactory.getSession();
                transaction=session.beginTransaction();
                num=Integer.parseInt(session.save(user).toString());
                transaction.commit(); //写入数据库,
            }catch (Exception e) {
                e.printStackTrace();
                num=0;
            }finally{//关闭session
                HibernateSessionFactory.closeSession();//调用HibernateSessionFactory的静态方法关闭Session
            }
            return num;
        }
    }

    基础类和他xml配置,简单样例。

    Users.java

    public class Users {
        private int id;
        private String name;
        private String password;
        private String sex;
        private int age;
        private String email;
        public Users(){
                
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }

    Users.hbm.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="com.ssh.models.Users" table="Users">
            <id name="id" column="id" > <!-- 配置主键 -->
                <generator class="native"/>
            </id>
            <!-- 配置其他属性 -->
            <property name="name" length="20"/>
            <property name="password" length="20"/>
            <property name="sex" length="2"/>
            <property name="age"/>
            <property name="email" length="50"/>
        </class>
    </hibernate-mapping>
  • 相关阅读:
    Android中的Looper , Handler , Message有什么关系
    理解Android系统的进程间通信原理(二)----RPC机制
    深入浅出JVM
    Linux个人常用命令汇总
    垃圾收集器与内存分配策略
    Linux上部署Java应用+Python3环境搭建
    List中remove元素的理解
    Java异常
    深入理解Java 8 Stream
    深入理解Java 8 Lambda
  • 原文地址:https://www.cnblogs.com/xuqiulin/p/10193609.html
Copyright © 2020-2023  润新知