Hibernate入门(附源代码,jar包)

来源:互联网 发布:詹姆斯数据排名 编辑:程序博客网 时间:2024/06/05 09:12

可以直接去我的下载页下载jar包(不要积分)http://download.csdn.net/detail/sdfiiiiii/5236307

源代码下载(不要积分)http://download.csdn.net/detail/sdfiiiiii/5236317

1. 安装eclipse hibernate 插件

http://download.jboss.org/jbosstools/updates/stable/
选择   JBoss Application Development    的     Hibernate Tools

2. 导入需要的包,目前使用的是struts2与hibernate,用到的包有:
antlr-2.7.6.jar
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
freemarker-2.3.19.jar
hibernate3.jar
javassist-3.11.0.GA.jar
javassist-3.4.GA.jar
jta-1.1.jar
log4j-1.2.14.jar
mysql-connector-java-5.0.3-bin.jar
ognl-3.0.6.jar
servlet-api.jar
slf4j-api-1.5.2.jar
slf4j-log4j12-1.5.2.jar
struts2-core-2.3.12.jar
xwork-core-2.3.12.jar

3. User.java,基本的POJO类
package com.login.vo;

public class User {
    private int id;
    private String username;
    private String password;
    private int isActive;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getIsActive() {
        return isActive;
    }
    public void setIsActive(int isActive) {
        this.isActive = isActive;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String toString(){
        return "id:"+this.id+"  username:"+this.username+"  password:"+this.password+"  isActive:"+this.isActive;
    }
}

4. 最典型的hibernate mapping文件可以是:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 07-Apr-2013 14:49:58 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.briup.hibernate.pojo" >
    <class name="com.login.vo.User"  table="users" >
        <id name="id" column="id">
        </id>
        <property name="username" column="name"></property>
        <property name="password" column="passwd"></property>
        <property name="isActive" column="isActive"></property>
    </class>
</hibernate-mapping>


5. 这里使用的是mysql数据库,如果数据库需要改变,那么在hibernate.cfg.xml文件中修改,基本配置可以写为
<?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">
<hibernate-configuration>
    <session-factory>
        <!-- 指定连接数据库所用的驱动 -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <!-- 指定连接数据库的url,hibernate连接的数据库名 -->
      <property name="connection.url">jdbc:mysql://localhost/test</property>
      <property name="connection.useUnicode">true</property>
      <property name="connection.characterEncoding">gbk</property>
      <!-- 指定连接数据库的用户名 -->
      <property name="connection.username">root</property>
      <!-- 指定连接数据库的密码 -->
      <property name="connection.password">123456</property>
      <!-- 指定连接池里最大连接数 -->
      <property name="hibernate.c3p0.max_size">20</property>
      <!-- 指定连接池里最小连接数 -->
      <property name="hibernate.c3p0.min_size">1</property>
      <!-- 指定连接池里连接的超时时长 -->
      <property name="hibernate.c3p0.timeout">1800</property>
      <!-- 显示Hibernate持久化操作所生成的SQL -->
            <property name="show_sql">true</property>
      <!-- 将SQL脚本进行格式化后再输出-->
        <property name="hibernate.format_sql">true</property>
        <mapping resource="com/briup/hibernate/pojo/Student.hbm.xml"/>
        <mapping resource="com/login/vo/Users.hbm.xml"/>
        <mapping resource="com/vo/usernote/kelvin/Notes.hbm.xml"/>
        <mapping resource="com/vo/usernote/kelvin/Categories.hbm.xml"/>
        
    </session-factory>
</hibernate-configuration>

6. 自己写的HibernateUtil.java类,用于封装一些常用的操作,未完善
package Util;
import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public final class HibernateUtil {   
    private static SessionFactory sessionFactory;   
    private static ThreadLocal session = new ThreadLocal();   
 
    public HibernateUtil() {   
    }   
 
    static {   
        Configuration cfg = new Configuration();   
        cfg.configure();   
        sessionFactory = cfg.buildSessionFactory();   
    }   
 
    public static Session getThreadLocalSession() {   
        Session s = (Session) session.get();   
        if (s == null) {   
            s = getSession();   
            session.set(s);   
        }   
        return s;   
    }   
 
    public static void closeSession() {   
        Session s = (Session) session.get();   
        if (s != null) {   
            s.close();   
            session.set(null);   
        }   
    }   
 
    public static SessionFactory getSessionFactory() {   
        return sessionFactory;   
    }   
 
    public static Session getSession() {   
        return sessionFactory.openSession();   
    }   
 
    public static void add(Object entity) {   
        Session s = null;   
        Transaction tx = null;   
        try {   
            s = HibernateUtil.getSession();   
            tx = s.beginTransaction();   
            s.save(entity);   
            tx.commit();   
        } finally {   
            if (s != null)   
                s.close();   
        }   
    }   
 
    public static void update(Object entity) {   
        Session s = null;   
        Transaction tx = null;   
        try {         
            s = HibernateUtil.getSession();   
            tx = s.beginTransaction();   
            s.update(entity);   
            tx.commit();   
        } finally {   
            if (s != null)   
                s.close();   
        }   
    }   
 
    public static void delete(Object entity) {   
        Session s = null;   
        Transaction tx = null;   
        try {   
            s = HibernateUtil.getSession();   
            tx = s.beginTransaction();   
            s.delete(entity);   
            tx.commit();   
        } finally {   
            if (s != null)   
                s.close();   
        }   
    }   
    
    public static List query(String queryString){
        Session s = null;
        List list = null;
        try {   
            s = HibernateUtil.getSession();   
            Query query = s.createQuery(queryString);
            list = query.list(); //搴忓垪鍖�            return list;
            return list;
        } finally {   
            if (s != null)   
                s.close();   
        }   
        
    }
 
    public static Object get(Class clazz, Serializable id) {   
        Session s = null;   
        try {   
            s = HibernateUtil.getSession();   
            Object obj = s.get(clazz, id);   
            return obj;   
        } finally {   
            if (s != null)   
                s.close();   
        }   
    }   
}  

7. JUnit测试类
import java.util.List;

import junit.framework.TestCase;
import Util.HibernateUtil;

import com.login.vo.User;
import com.vo.usernote.kelvin.Notes;

public class TestHibernate extends TestCase {
    public void testUser(){
        @SuppressWarnings("unchecked")
        List<User> usersList = HibernateUtil.query("from User");
        for(User user: usersList){
            System.out.println(user.toString());
        }
    }
    
    public void testNotes(){
        List<Notes> notesList = HibernateUtil.query("from Notes");
        for(Notes note: notesList){
            System.out.println(note.toString());
        }
    }
}