首页 > 代码库 > hibernate学习2_简单hibernate实现

hibernate学习2_简单hibernate实现

本文通过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实现