1. 创建POJO类;
package chen;
public class Student {
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}
2.编写映射文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="chen.Student" table="student">
<id name="id" column="sid" type="java.lang.String">
</id>
<property name="name" type="java.lang.String">
<column name="sname" length="10"/>
</property>
<property name="age" type="java.lang.Integer">
<column name="sage" />
</property>
</class>
</hibernate-mapping>
3.编写Hibernate配置文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/school</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="show_sql">true</property>
<mapping resource="chen/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.测试
package chen;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class testhiber {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration config=new Configuration().configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Student student=new Student();
student.setId("8888");
student.setName("张三");
student.setAge(24);
//开启Session,相当于开启JDBC的Connection
Session session=sessionFactory.openSession();
//Transaction 表示一组对DB的交易
Transaction tx=session.beginTransaction();
session.save(student);
tx.commit();
System.out.println("新增人员成功!");
}
}
当然,还要添加Hibernate包和数据库驱动包。
程序文档结构图:
Could not parse mapping document from resource Event.hbm.xml原因 :
错误原因:主要是我们拷贝配置头文件的时候,我们大意了,没有区别他们。
注意:一个是配置文件的头文件,一个是映射文件的头文件。如下红色部分各自配置就不会报错了。
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
Event.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">