001 :hibernate第一个helloword(映射)

来源:互联网 发布:淘宝骗局怎么处理 编辑:程序博客网 时间:2024/05/17 22:41

create database hibernate;

create table student(id int primary key,

                                       name varchar(20),

                                        age int);

下载hibernate3.3.2

下载slf4j.1.5.8

 

新建自己的工程:

    1、右键---new ---project(java project)---hibernate_0100

    2、 技术:引入jar包的方式(hibernate jar)

              windows---preferences----java----build path----user libraries---new ----【hibernate】---add JARS

               (1)\hibernate3.jar

               (2)\lib----required---jar

               (3)\slf4j-1.5.8----slf4j-nop-1.5.8.jar

               总共8个包

        【引入个体包:右键----build path---add external archives】

     3、右键---build path---add---libraries---user library----hibernate

    4、引入连数据库的jar包

           右键---build path----add External Archives---mysql-connector-java-3.2.0-bin.jar

     5、在mysql中建 立对应的数据库

      5 、建student类:

              src----new ----class----package :com.bjsxt.hibernate.model

                                                      class:student

           [如果想把student存到数据库里去,这些属性需要跟数据库里一一对应]

            

package com.bjsxt.hibernate.model;public class Student {      private int id;      private String name;      private int age;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 int getAge() {return age;}public void setAge(int age) {this.age = age;}      }


6、建立student.Test用main来写测试

 7、建立hibernate配置文件,hibernate.cfg.xml

     a)、从参考文档中copy

     b)、修改对应的数据库连接

      c)、注释掉暂时用不上的内容

      src----new----file----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>        <!-- Database connection settings -->        <!-- 连接数据库 -->        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>        <property name="connection.username">root</property>        <property name="connection.password">root</property>        <!-- JDBC connection pool (use the built-in) -->        <!-- 自带的 连接池,暂不用-->        <!--  <property name="connection.pool_size">1</property>-->        <!-- SQL dialect -->        <!-- 改为mysql方言 -->        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <!-- Enable Hibernate's automatic session context management -->        <!--  <property name="current_session_context_class">thread</property>-->                <!-- Disable the second-level cache  -->        <!-- 把二级缓存disable掉 -->        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        <!-- Echo all executed SQL to stdout -->        <!-- 把生成的sql语句打印出来 -->        <property name="show_sql">true</property>        <!-- Drop and re-create the database schema on startup -->        <!-- 要不要hibernate 自动生成建表语句 -->        <!--  <property name="hbm2ddl.auto">update</property> -->        <mapping resource="com/bjsxt/hibernate/model/Student.hbm.xml"/>    <mapping class="com.bjsxt.hibernate.model.Teacher"/>    </session-factory></hibernate-configuration>


8、建立student映射文件Student.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="com.bjsxt.hibernate.model"><class name="Student" table="student"><id name="id" ></id><property name="name"></property><property name="age"></property>    </class></hibernate-mapping>


  (1)、src---new---file---Student.hbm.xml

       其中:<class name="Student" table="student">

               </class>

        意为:名字叫Student的这个类对应的表中student

        【如果实体类的名字和表名一样,直接写一个class就可以】

 (2)、<id name="id"  column="id"></id>

             id为表的主键,name=id,指类里面的属性getId(),

             column="id",对应的数据库表里面的Id为id

   (3)、<property name="name"></property>

          非主键的属性,指在class里面有一个成员变量叫name,对应的表里面字段的名字也叫做name

 

整体作用是让class和表对应起来。

9、告诉hibernate.cfg.xml去哪里找这个配置文件

 <mapping resource="com/bjsxt/hibernate/model/Student.hbm.xml"/>

10、通过configurate对象,拿到sessionFactory再拿到session.

   在studentTest中:

 

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.bjsxt.hibernate.model.Student;public class StudentTest {   public static void main(String[]args){   Student s=new Student();      //往数据库里面存值   s.setId(1);   s.setName("s1");   s.setAge(1);      //开始拿到session   /*首先要拿到configuration    * configuration cfg=new configuration();    * 用onfigurationy读配置文件,可以指定读哪个文件(Document,String,url)    * 如果不指定,默认就 是libernate.cfg.xml下面的    */  Configuration cfg=new Configuration();      SessionFactory sf= cfg.configure().buildSessionFactory();          Session session=sf.openSession();   session.beginTransaction();   session.save(s);   session.getTransaction().commit();//提 交      session.close();//关闭session      sf.close();//关闭工厂   }   }


测试:右键----run as ---java Appliation

 

异常:

1 Exception in thread "main" org.hibernate.TransactionException: Transaction not successfully started

分析:
这个错误的产生是因为我在保存entity后提交事务用的session.getTransaction().commit()语句,session.getTransaction()只是根据session获得一个Transaction实例,但是并没有启动它,所以它会告诉你“Transaction启动失败”(Transaction not successfully started)

解决:
应该用session.beginTransaction()代替session.getTransaction(),session.beginTransaction()方法在获得一个Transaction后调用其begin()方法,如果是请求创建一个新的“受控”Transaction,则启动这个Transaction,否则就直接使用已经存在的“受控”Transaction来完成工作。

 

技巧:引包的快捷键:ctrl+shift+o

            对类的重命名用F2

流程:

       拿到configuration,sessionFactory.session后,执行save(),方法的时候,hibernate发现,这是一个Student类,就 会去找Student类的配置文件(libernate.cfg.xml)中的
 <mapping resource="com/bjsxt/hibernate/model/Student.hbm.xml"/>,然后save(id,name,age)

 

 

 

 

0 0
原创粉丝点击