hibernate基本概念及初始配置







************************

hibernate.cfg.xml

***********************

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

<hibernate-configuration>

   <session-factory>
   		<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
   		<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property><!-- ///表示连接本机的数据库localhost://3306 -->
   		<property name="hibernate.connection.username">root</property>
   		<property name="hibernate.connection.password">1234</property>
   		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- 数据库方言 -->
   		
   		<property name="hibernate.hbm2ddl.auto">update</property><!-- 让hibernate自动生成ddl -->
   		<property name="hibernate.show_sql">true</property>
   		<mapping resource="blog/hibernate/domain/User.hbm.xml"/>
   </session-factory>
	
	
</hibernate-configuration>


************************

User.java

***********************

package blog.hibernate.domain;

import java.util.Date;

public class User {
	private int id;
	private String name;
	private Date birthday;
	
	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 Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	
}




***********************

User.hbm.xml

***********************

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

<hibernate-mapping package="blog.hibernate.domain">
	<class name="User" table="USERS">
		<id name="id" column="USER_ID">
			<generator class="native"></generator>
		</id>
		<property name="name" column="USER_NAME" type="string"></property>
		<property name="birthday" column="BIRTHDAY" type="timestamp"></property>
	</class>
</hibernate-mapping>

**********************

HibernateUtil.java

**********************

package blog.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import blog.hibernate.domain.User;

public final class HibernateUtil {
    
    private static SessionFactory sessionFactory;
    private HibernateUtil(){}
    
    static{
        Configuration cfg = new Configuration();
        sessionFactory =  cfg.configure("hibernate.cfg.xml").buildSessionFactory();
    }
    
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
    
    public static Session getSession(){
        return sessionFactory.openSession();
    }
    
    public static Object get(Class clazz,int Id) throws Exception {
        Session session = null;
        Object object = null;
        try {
            session = getSession();
            object = session.get(clazz, Id);
            //object = session.load(class, userId);
            return object;
        } catch (HibernateException e) {
            e.printStackTrace();
            throw e;
        }finally{
            session.close();
        }
    }

    public static void add(Object object) throws Exception {
        Session session = null;
        Transaction tx = null;
        try {
            session = getSession();
            tx = session.beginTransaction();// 相当于tx =session.getTransaction();tx.begin();
            session.save(object);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
    
    public static void update(Object object) throws Exception {
        Session session = null;
        Transaction tx = null;
        try {
            session = getSession();
            tx = session.beginTransaction();// 相当于tx =session.getTransaction();tx.begin();
            session.update(object);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
    
    public static void delete(Object object) throws Exception {
        Session session = null;
        Transaction tx = null;
        try {
            session = getSession();
            tx = session.beginTransaction();// 相当于tx =session.getTransaction();tx.begin();
            session.delete(object);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
    
    /**
     * 用HQL实现
     * @param username
     * @return User
     */
    public static User get(String username){
        Session session = null;
        try {
            session = getSession();
            //1、String hql = "from User as user where user.name = ?";//User 为类 而不是表名
            String hql = "from User as user where user.name =:name";
            Query query = session.createQuery(hql);
            //1、query.setString(0, username);
            query.setString("name", username);
            User user = (User)query.uniqueResult();
            
            List<User> users = query.list();
            
            /*//用于分页,可以针对不同的数据库
            query.setFirstResult(0);
            query.setMaxResults(10);*/
            return user;
        } catch (HibernateException e) {
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
    
    /**
     * 用Criteria接口实现
     * @param username
     * @return List<User>
     */
    @SuppressWarnings("unchecked")
    public static List<User> query(){
        Session session = null;
        try {
            session = getSession();
            Criteria criteria = session.createCriteria(User.class);
            //criteria.add(Restrictions.eq("name",username));
            criteria.add(Restrictions.lt("birthday", new Date()));
            
            List<User> users = criteria.list();
            /*//分页
            criteria.setFirstResult(0);
            criteria.setMaxResults(10);*/
            return users;
        } catch (HibernateException e) {
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
}



*************************

Base.java

*************************

package blog.hibernate;

import java.util.Date;

import blog.hibernate.domain.User;

public class Base {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List<User> users = HibernateUtil.query();
            for (User user : users) {
                System.out.println(user.getName());
                System.out.println(users.size());
                System.out.println("*****************************");
            }
	}

}




posted @ 2012-08-14 08:51  xzf007  阅读(177)  评论(0编辑  收藏  举报