Hibernate框架的基本搭建(一个小的java project的测试向数据库中插入和查询数据的功能)

Hibernate介绍:Hibernate是一种“对象-关系型数据映射组件”,它使用映射文件将对象(object)与关系型数据(Relational)相关联,在Hibernate中映射文件通常以".hbm.xml"作为后缀。

包:com.cn.beans

与数据库表t_user(id主键,name)对应的工程中POJO代码(Javabean):Tuser.Java

package com.cn.beans;
import java.io.Serializable;

import javax.annotation.Generated;


public class Tuser implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    
    
}



POJO与数据库表对应的映射文件:Tuser.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" >
<hibernate-mapping package="com.cn.beans">
<class name="com.cn.beans.Tuser" table="t_user">
<id name="id" column="id" type="int">

</id>
<property name="name" column="name" type="string">
</property>
</class>
</hibernate-mapping>

 

包:com.cn.hibernate.test:HibernateBaseTest.java代码:

package com.cn.hibernate.test;


import java.util.List;

import junit.framework.Assert;
import junit.framework.TestCase;

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

import com.cn.beans.Tuser;


public class HibernateBaseTest{
    Session session=null;
    
    //初始化hibernate的Session
    protected void setUp(){
        try{
            Configuration config=new Configuration().configure();
            SessionFactory sessionFactory=config.buildSessionFactory();
            session = sessionFactory.openSession();
            System.out.println("连接数据库成功!");
        }catch(HibernateException e){
            e.printStackTrace();
            System.out.println("连接数据库失败!");
        }
    }
    
    public static void main(String[] args) {
        HibernateBaseTest j = new HibernateBaseTest();
        j.setUp();
        //j.testInsert();
        j.testSelect();
    }
    //teardown()方法用于关闭用setUp打开的hibernate中的Session;
    protected void teardown(){
     try{
         session.close();
         System.out.println("关闭数据库");
     }catch(HibernateException e){
         e.printStackTrace();
     }
 }
  
    
    public void testInsert(){
        Transaction    tran=null;
            try{
            tran=session.beginTransaction();
            Tuser user=new Tuser();
            user.setId(8);
            user.setName("Emma11");
            session.save(user);
            session.flush();
            tran.commit();
            session.close();
        }catch(HibernateException e){
            e.printStackTrace();
            if(tran!=null){
                try{
                tran.rollback();
               }catch(HibernateException e1){                    
                   e1.printStackTrace();
               }
           }
        }
    } 
    
    
    
    //对象读取(select)测试,请保证运行之前数据库中已经存在name='Emma11'的记录
    
    public void testSelect(){
        //setUp();
        String hql="from Tuser where name='Emma11'";
        try{
            List userList=session.createQuery(hql).list();
            Tuser user=(Tuser)userList.get(0);
            //Assert.assertEquals(user.getName(), "Emma11");
            System.out.println("用户为:"+user.getId()+" "+user.getName());
        }catch(HibernateException e){
            e.printStackTrace();
            //Assert.fail(e.getMessage());
        }
        teardown();
    }
}

 

测试类:JunitTest.java

package com.cn.hibernate.test;
import org.junit.Test;

public class JunitTest {
       

    @Test
    public void testInsert() {
    }
    
    @Test
    public void testselect() {
    }
    
}

 

该包对应的文件:

1.hibernate.cfg.xml(与sql server2008数据库进行连接的配置文件)

<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--显示执行的SQL语句-->
<property name="hibernate.show_sql">true</property>
<!--连接字符串-->
<property name="hibernate.connection.url">
jdbc:sqlserver://192.168.254.133:1433;DatabaseName=sample
</property>
<!--连接数据库的用户名-->
<property name="hibernate.connection.username">sa</property>
<!--数据库用户密码-->
<property name="hibernate.connection.password">123456</property>
<!--数据库连接池的大小-->
<property name="hibernate.connection.pool.size">20 </property>
<!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->
<property name="jdbc.fetch_size">50</property>
<!--数据库驱动-->
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<!--选择使用的方言-->
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>

<!-- <property name="connection.pool_size">0</property> -->
<property name="c3p0.max_size">2000</property>
<property name="c3p0.min_size">200</property>
<property name="c3p0.timeout">5000</property>
<property name="c3p0.validate">false</property>
<!--
<property name="hibernate.transaction.factory_class">
net.sf.hibernate.transaction.JDBCTransactionFactory
</property>
-->
<!-- Enable Hibernate's automatic session context management -->
<!--<property name="current_session_context_class">thread</property>

--><property name="connection.autocommit">true</property>

<!--在启动时删除并重新创建数据库-->
<mapping resource="com/cn/beans/Tuser.hbm.xml"/>
</session-factory>
</hibernate-configuration>

 

结果:插入记录

查询记录:

posted @ 2015-10-09 17:00  乱码建  阅读(211)  评论(0)    收藏  举报