Hibernate入门HelloWorld程序编写

从http://hibernate.org/orm/官网下载hibernate,该文章里面用的是hibernate4.3.11

用eclipse或者myeclipse创建一个project,在src下面创建一个hibernate的xml文件,名字为hibernate.cfg.xml

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


<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
</session-factory>
</hibernate-configuration>

然后创建一个类,一个实体,本文用的User包括id,name,password,添加get和set方法。

在mysql数据库里面创建一个对应的表,也是包括id,name,password,

添加一个配置文件,将user和表对应起来,代码如下:

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <hibernate-mapping>
  <class name="com.beijing.po.User" table="t_user">
  <id name="id" column="id">
  <generator class="native"></generator>
  </id>
  <property name="name" column="name"></property>
  <property name="password" column="password"></property>
  </class>
 </hibernate-mapping> 

完成以上步骤后需要在hibernate配置文件添加标签,添加后的标签为

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


<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>

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

<mapping resource="com/beijing/po/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

添加测试类,测试一下是否能够完成,代码如下:

package com.beijing.test;




import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


import com.beijing.po.User;


public class TestClient {


public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg = cfg.configure();

SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();

User user = new User();
user.setName("河北");
user.setPassword("4123");
session.save(user);

tx.commit();

}


}

这样一个hibernate的HelloWord就创建完成。

总的目录结构为

注:在hibernate的配置文件添加mapping时,起始目录默认为src根部。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值