hibernate小小demo

开发流程:

1 下载并安装Hibernate

2 Hibernate配置文件详解 配置与MySQL数据库的链接与映射文件User.hbm.xml

3 生成映射文件User.hbm.xml

4 编写持久化类User.java

5 编写辅助类HibernateSessionFactory.java 负责取得和关闭Hibernate的Session对象

6 编写DAO类UserDAO.java 编写根据用户名取得用户对象的getUser()

7 编写Service类UserService.java 编写valid()函数 调用UserDAO.java的getUser()函数执行函数验证


  1. 下载并安装Hibernate

    hibernate-3.0.zip

  2. hibernate.cfg.xml配置文件:

  3. <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <!-- Generated by MyEclipse Hibernate Tools. -->
    <hibernate-configuration>
    
        <session-factory>
            <property name="myeclipse.connection.profile">
                JDBC for MySQL
            </property>
            <property name="connection.url">
                jdbc:mysql://localhost:3306/demo
            </property>
            <property name="connection.username">root</property>
            <property name="connection.password">root</property>
            <property name="connection.driver_class">
                org.gjt.mm.mysql.Driver
            </property>
            <property name="dialect">
                org.hibernate.dialect.MySQLDialect
            </property>
            <mapping resource="com/demo/hibernate/beans/User.hbm.xml" />
    
    
        </session-factory>
    
    </hibernate-configuration>



3. User.hbm.xml

<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration. -->
<!-- Created Tue Aug 14 18:57:22 CST 2007 -->
<hibernate-mapping package="com.demo.hibernate.beans">

    <class name="User" table="user">
        <id name="id" column="ID" type="integer">
            <generator class="native"/>
        </id>

        <property name="username" column="username" type="string" />
        <property name="password" column="password" type="string" />
        <property name="email" column="email" type="string" />
    </class>
    
</hibernate-mapping>

4.User.java:

package com.demo.hibernate.beans;

public class User {
    private java.lang.Integer id;

    private java.lang.String username;

    private java.lang.String password;

    private java.lang.String email;

    public java.lang.String getEmail() {
        return email;
    }

    public void setEmail(java.lang.String email) {
        this.email = email;
    }

    public java.lang.Integer getId() {
        return id;
    }

    public void setId(java.lang.Integer id) {
        this.id = id;
    }

    public java.lang.String getPassword() {
        return password;
    }

    public void setPassword(java.lang.String password) {
        this.password = password;
    }

    public java.lang.String getUsername() {
        return username;
    }

    public void setUsername(java.lang.String username) {
        this.username = username;
    }

}

5.HibernateSessionFactory.java

package com.demo.hibernate.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution. Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html}.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * NOTICE: Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file. That
     * is place the config file in a Java package - the default location
     * is the default Java package.


     * Examples: 

     * CONFIG_FILE_LOCATION = "/hibernate.conf.xml". 
     * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml". 
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

    /** Holds a single instance of Session */
    private static final ThreadLocal threadLocal = new ThreadLocal();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
     * Returns the ThreadLocal Session instance. Lazy initialize
     * the SessionFactory if needed.
     *
     * @return Session
     * @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null) {
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%");
                    e.printStackTrace();
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }

        return session;
    }

    /**
     * Close the single hibernate session instance.
     *
     * @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     * Default constructor.
     */
    private HibernateSessionFactory() {
    }

}

6.UserDAO.java

package com.demo.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.demo.hibernate.beans.User;
import com.demo.hibernate.util.HibernateSessionFactory;

public class UserDAO {

    public User getUser(String username) throws HibernateException {
        Session session = null;
        Transaction tx = null;
        User user = null;
        try {
            session = HibernateSessionFactory.currentSession();
            tx = session.beginTransaction();
            Query query = session.createQuery("from User where username=?");
            query.setString(0, username.trim());
            user = (User)query.uniqueResult();
            query = null;
            tx.commit ();
        }catch(HibernateException e){
            throw e;
        }finally{
            if (tx!=null) {
                tx.rollback();
            }
            HibernateSessionFactory.closeSession();
        }
        return user;
    }
}


7.UserService.java

package com.demo.hibernate.service;

import com.demo.hibernate.beans.User;
import com.demo.hibernate.dao.UserDAO;

public class UserService {
    
    public boolean valid(String username, String password) {
        UserDAO test = new UserDAO();
        User user = test.getUser("admin");
        if(user.getPassword().equals(password)) {
            return true;
        } else {
            return false;
        }
    }
    
    public static void main(String[] args) {
        UserService service = new UserService();
        boolean login = service.valid("admin", "admin");
        System.out.println("验证结果:"+login);
    }
}



你可能感兴趣的:(hibernate小小demo)