一个first Hibernate 测试

来源:互联网 发布:如何进入sm圈子知乎 编辑:程序博客网 时间:2024/05/22 00:24

Develop IDE

:Eclipse ,  SQL 2000, Hibernate 3.6

Eclipse 安装Hibernate 插件:hibernate tools-indogo 文件夹copy到eclipse dropins文件夹下.

1.新建数据库person , 新建数据表person

2.新建JAVA Project :HibernateTest

导入相关.jar包

hibernate3.jar

antlr-2.7.6.jar

commons-collection-3.1.jar

dom4j-1.6.1.jar

javassist-3.12.0.GA.jar

jta-1.1.jar

slf4j-api-1.6.1.jar

slf4j-nop-1.6.2.jar

jtds-1.2.5.jar

hibernate-jpa-2.0-api-1.0.1.Final.jar

3.新建类 (get,set)

4.新生成:.hbm.xml配制文档.

5.新后成: cfg.xml连接数据库,因为是用jtds jar包的,所以连接URL: net.sourceforge.jtds.jdbc.Driver

 

<session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:jtds:sqlserver://127.0.0.1:1433/Person</property>  
        <property name="connection.username">sa</property>
        <property name="connection.password">1</property>
        <!-- JDBC connection pool (use the built-in)-->
        <!-- <property name="connection.pool_size">1</property> -->
        <!-- 指定使用SQL数据库格式的SQL语句 dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
        <!--要加这一句,否则可能会遇到异常 Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache  -->
        <!-- <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> -->
        <!-- 指定在控制台打印生成SQL语句 Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- 指定Hibernate启动的时候自动创建表结构Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

      <!--指定Person类为Hibernate实体类-->
        <mapping  resource="Person.hbm.xml"/>
    </session-factory>

6.新建Hibernate工具类..

import org.hibernate.SessionFactory;
import org.hibernate.cfg.*;

public class HibernateUtil {
 private static final SessionFactory sessionFactory=buidSessionFactory(); //单态模式的SessionFactory
 
 private static SessionFactory buidSessionFactory(){
 
  return new Configuration().configure().buildSessionFactory();
};


public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

 

7.执行Hibernate程序

import org.hibernate.Session;

import util.HibernateUtil;
public class TestPerson {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Session ss=HibernateUtil.getSessionFactory().getCurrentSession();
  ss.beginTransaction();
     Person Hh=new Person();
     Hh.setId("001");
     Hh.setName("user1");
     Hh.setAge("20");
    ss.save(Hh);
   ss.getTransaction().commit();
 }

}

 

原创粉丝点击