Hibernate入门--环境的搭建

搭建hibernate环境

1、新建java项目

2、导入相关jar包

  • 2.1路径

  

  • 2.2添加进项目

  

 3、编写配置文件hibernate.cfg.xml

  • 3.1  复制hibernate资源中的hibernate.cfg.xml,路径为

  

  • 3.2,详细配置情况在下图路径中可查看

  

  • 3.3,例如配置数据库和sql语言

  (注:若不显示提示,导入下图中的路径)

  

  • 3.4,数据库语言的选择路径

  

4、创建数据库,以及对应pojo对象

public class User {

    private Integer id;

    private String name;

    private String pwd;

  省略get、set方法

}

          

 

 

 

 

 

   User表

Id

Name

Pwd

 

 

 

      

 

 

5、编辑*.hbm.xml配置文件

             5.1 文件名一半为pojo类名称:如:User.hbm.xml

             5.2 放在pojo类所在包下

    

 

            5.3 头文件可以在hibernate资源下查找

     

  • 5.4 编辑*.hbm.xml

  

6、测试:将*.hbm.xml配置文件加入到hibernate.cfg.xml配置文件中

 

测试类:

public class HibernateTest {

    public static void main(String[] args) {

       // 1、新建Configuration对象

       Configuration cfg = new Configuration().configure();

       // 2、通过Configuration对象创建SessionFactory

           //在hibernate3.x中是这样写

           //SessionFactory sf = cfg.buildSessionFactory();

       // hibernate4.3

       ServiceRegistry sr = new StandardServiceRegistryBuilder()

                                  .applySettings(cfg.getProperties()).build();

       SessionFactory sf = cfg.buildSessionFactory(sr);

       // 3、通过SessionFactory得到Session

       Session session = sf.openSession();

       // 4、通过Session对象得到Transaction对象

       Transaction tx = session.beginTransaction();

       // 5、保存数据

       User user = new User();

       user.setName("张三");

       user.setPwd("111");

       session.save(user);

       // 6、提交事务

       tx.commit();

       // 7、关闭session

       session.close();

    }   

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

结果:

 

 

 

 

 

posted @ 2018-06-29 21:44  莯汐  阅读(66)  评论(0编辑  收藏  举报