一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java中Hibernate中的数据库对象详解

时间:2013-11-03 编辑:简简单单 来源:一聚教程网

1.hibernate.cfg.xml

 代码如下 复制代码

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



   
    org.hibernate.dialect.MySQLDialect
   
    com.mysql.jdbc.Driver
   
    root
   
    word">root
   
    jdbc:mysql://localhost:3306/hibernate
   
    20
   
    1
   
    5000
   
    true
   
    true
   
    true

    100
    3000
    2
    true
   
    create
   
   


2.持久化类 pen.java

 代码如下 复制代码

package org.Rudiment.hibernate;

public class pen {
    private int id;
    private int price;
    private String type;
   
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
}

3. 持久化类的映射文件 pen.cfg.xml

 代码如下 复制代码


"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


   
       
           
           
       

       
           
       

       
           
       

   

   
   
       
        create table test(t_name varchar(255));
       
        drop table test
       
       
       
   


4.操作持久化类的处理类 penHandler.java

 代码如下 复制代码

package org.Rudiment.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class penHandler {
    public static void main(String[] args)
    {
        Configuration conf = new Configuration();
        conf.configure();
        ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
        SessionFactory sf = conf.buildSessionFactory(sr);
    }
}


注:

通过上面可以看出,penHandler中的main只是执行到了conf.buildSessionFactory(sr);这个时候我们在配置文件中的这部分配置就生效了。

 代码如下 复制代码


   
    create table test(t_name varchar(255));
   
    drop table test
   
   
   

查看数据库的时候,看到表已经成功建立起来了。

 代码如下 复制代码

mysql> desc test;
+--------+--------------+------+-----+---------+-------+
| Field  | Type         | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| t_name | varchar(255) | YES  |     | NULL    |       |
+--------+--------------+------+-----+---------+-------+
1 row in set (0.02 sec)

最后还有一点要注明的就是代码要执行到conf.buildSessionFactory(sr);如果条代码从main中给删除掉了,那么hibernate将不会执行数据库对象,即如果要让数据库对象生效,至少需要执行到conf.buildSessionFactory(sr);这一条代码。

热门栏目