目录结构
类
package com.hibernate.helloworld;public class School { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public School(String name, String address) { super(); this.name = name; this.address = address; } public School() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "School [name=" + name + ", address=" + address + "]"; } }package com.hibernate.helloworld;import java.util.Date;public class Student { private Integer id; private String name; private Date birth; private School school; public Student() { // TODO Auto-generated constructor stub } public Student(String name, Date birth) { super(); this.name = name; this.birth = birth; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", birth=" + birth + ", school=" + school + "]"; } }
hibernate.cfg.xml
root 1 com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8 org.hibernate.dialect.MySQLInnoDBDialect true true update
Student.hbm.xml
Test
package com.hibernate.helloworld;import java.sql.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import org.junit.Test;public class test { @Test public void test() { System.out.println("test..."); //1. 创建一个 SessionFactory 对象 SessionFactory sessionFactory = null; //1). 创建 Configuration 对象: 对应 hibernate 的基本配置信息和 对象关系映射信息 Configuration configuration = new Configuration().configure(); //4.0 之前这样创建// sessionFactory = configuration.buildSessionFactory(); //2). 创建一个 ServiceRegistry 对象: hibernate 4.x 新添加的对象 //hibernate 的任何配置和服务都需要在该对象中注册后才能有效. ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); //3). sessionFactory = configuration.buildSessionFactory(serviceRegistry); //2. 创建一个 Session 对象 Session session = sessionFactory.openSession(); //3. 开启事务 Transaction transaction = session.beginTransaction(); //4. 执行保存操作 Student student = new Student("刘备", new Date(new java.util.Date().getTime())); School school = new School("AAA","BBB"); student.setSchool(school); session.save(student); //5. 提交事务 transaction.commit(); //6. 关闭 Session session.close(); //7. 关闭 SessionFactory 对象 sessionFactory.close(); } }