1. Open myeclipse, create a Java project, and import the jar package required by Hibernate and the jar of the MySQL database driver;
For the required jar, see blog http://blog.csdn.net/spring292713/article/details/8119159
Create a database hibernate.
2. Create a pojo class, student. Java
package com.hibernate._0100_introduce;public class Student {private int id;private String name;private int age;public int getId() {return id;}public void setId(int 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;}}
3. Create a New hibernate. cfg. xml file and write the following content:
<?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">
4. Compile the student. HBM. xml file.
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
The table attribute in the class label can specify the name of the table corresponding to the object class in the database. If it is not specified, it is the same as the table name by default;
Id label is used to represent the primary key. The generator attribute is used to specify the ID growth policy. The value of the policy is related to the ID field type;
The propetry tag specifies other fields to be mapped to the database table. If a field is not specified here, this field is not found in the generated table;
The column attribute specifies the name of the field in the database table. If this parameter is not specified, it is the same as the attribute name in the class by default;
5. Add the student. HBM. xml configuration file to the hibernate. cfg. xml file. The preceding configuration file has been added.
6. Write test. Java
import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Test {public static void main(String[] args) {Student s = new Student();s.setName("zhangsan");s.setAge(8);SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession();session.beginTransaction();session.save(s);session.getTransaction().commit(); session.close; }}