现在的位置: 首页 > 综合 > 正文

Eclipse3.4+Hibernate3.3.1连接Sql Server数据库

2013年09月19日 ⁄ 综合 ⁄ 共 2424字 ⁄ 字号 评论关闭

1.       创建一个实体类,对应数据库的每个表,User.java

2.       创建实体类相对应的映射文件,User.hbm.xml

3.       创建Hibernate相对应的配置文件Hibernate.cfg.xml或者Hibernate.properties

4.       创建数据库类,ExportDB.java

 

附源代码:

User.java

package com.hibernate01;

 

public class User {

 

    private int id;

    private String username;

    private String password;

    private String address;

    public int getId() {

       return id;

    }

    public void setId(int id) {

       this.id = id;

    }

    public String getUsername() {

       return username;

    }

    public void setUsername(String username) {

       this.username = username;

    }

    public String getPassword() {

       return password;

    }

    public void setPassword(String password) {

       this.password = password;

    }

    public String getAddress() {

       return address;

    }

    public void setAddress(String address) {

       this.address = address;

    }

}

 

 

User.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.hibernate01">

  <class name="User" table="HiSoft">

  <id name="id" column="id">

    <generator class="native"></generator>

  </id>

  <property name="username" column="username" length="20"/>

  <property name="password" column="password" length="15"/>

  <property name="address" column="address" length="50"/>

  </class>

 

</hibernate-mapping>

 

ExportDB.java

package com.hibernate01;

 

import org.hibernate.cfg.Configuration;

import org.hibernate.tool.hbm2ddl.SchemaExport;

 

public class ExportDB {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

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

       SchemaExport export = new SchemaExport(cfg);

       export.create(true, true);

 

 

    }

 

}

 

 

Hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC

    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

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

 

<hibernate-configuration>

    <session-factory>

       <!-- 是否显示SQL语句 -->

        <property name="show_sql">true</property>

        <!-- SQL数据库方言SQLServer -->

        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

        <!--   JDBC Driver -->

        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>

        <!-- JDBC URL -->

        <property name="connection.url">jdbc:sqlserver://hiof-shuait-l/sql2008;databaseName=hibernate;selectMethod=Cursor;</property>

        <!-- 用户名-->

        <property name="connection.username">sa</property>

        <!-- 密码 -->

        <property

抱歉!评论已关闭.