1. 程式人生 > >hibernate連線資料庫和使用

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>