首页 > 代码库 > 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>
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; } }
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>
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(); }}
运行结果
hibernate学习2_简单hibernate实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。