1.配置hibernate.cfg.xml,使用的数据库是mysql

  

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <property name="connection.url">
        jdbc:mysql://localhost:3306/test
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">tcl#0622</property>
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="myeclipse.connection.profile">jerry</property>
    <property name="show_sql">true</property>
    <mapping resource="entity/Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

2.新建一个实体类 Student.java

package entity;

import java.io.Serializable;

public class Student implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 3460725921094026801L;
    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;
    }
}


3.配置mapping关系表 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="entity">
    <class name="Student" table="t_student">
        <id name="id" column="id" type="java.lang.Integer">
            <generator class="identity"></generator>
        </id>
        <property name="name" column="name" type="java.lang.String" not-null="true"></property>
        <property name="age" column="age" type="java.lang.Integer" not-null="true"></property>
    </class>
</hibernate-mapping> 

4.写一个测试类

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestStudent {
    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        SchemaExport export = new SchemaExport(configuration);
        export.create(true, true);
    }
    
}

5.执行,mysql查看表也新建工程。

posted on 2013-03-11 22:18  爱生活的夜  阅读(195)  评论(0编辑  收藏  举报