码迷,mamicode.com
首页 > Web开发 > 详细

hibernate学习2_简单hibernate实现

时间:2014-12-27 01:29:22      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

本文通过java工程+hibernate简单实现了一个hibernate持久化java对象到mysql数据库的功能。

1、工程配置

技术分享

 

2、数据库连接配置文件hibernate.cfg.xml

技术分享
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.djl.test">
    <class name="Student" table="student">
      <id name="id" column="ID">
      </id>
      <property name="name" column="name" type="string"/>
      <property name="age" column="age" type="integer"/>
    </class>
</hibernate-mapping>
View Code

3、新建对应java实体Student.java

技术分享
package com.djl.test;

public class Student {
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    private String name;
    private int age;
    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;
    }
    
}
View Code

4、建立实体与数据库对应映射关系 student.hbm.xml

技术分享
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.djl.test">
    <class name="Student" table="student">
      <id name="id" column="ID">
      </id>
      <property name="name" column="name" type="string"/>
      <property name="age" column="age" type="integer"/>
    </class>
</hibernate-mapping>
View Code

5、简单测试程序进行调用

技术分享
package com.djl.test;

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

public class MainTest {
    public static void main(String... args){
        Student stu = new Student();
        stu.setId(0);
        stu.setAge(20);
        stu.setName("wangshan");
        Configuration config = new Configuration();
        config.configure();
        SessionFactory factory =  config.buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction(); 
        session.save(stu);
        session.getTransaction().commit();
        session.close();
        factory.close();        
    }
}
View Code

 

运行结果

 

技术分享

hibernate学习2_简单hibernate实现

标签:

原文地址:http://www.cnblogs.com/toDjlPersonnalBlog/p/4187904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!