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(); } }
运行结果
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。