1.项目示例如图:
2.studentClass.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">
<!-- Generated 2016-7-20 10:48:06 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eduask.pojo.StudentClass" table="StudentClass">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
</class>
</hibernate-mapping>
3.student.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">
<!-- Generated 2016-7-20 10:48:06 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eduask.pojo.Student" table="student">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<!--多对一 -->
<many-to-one name="studentClass" class="com.eduask.pojo.StudentClass" column="studentClass_id">
</many-to-one>
</class>
</hibernate-mapping>
4.测试类:
package com.eduask.test;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.Test;
import com.eduask.pojo.Student;
import com.eduask.pojo.StudentClass;
import com.eduask.util.HibernateUtil;
public class StudentTest {
private SessionFactory sessionFactory;
@Before
public void setUp() throws Exception {
//使用hibernateUtil工具类来创建单例的sessionFactory 对象
//再使用sessionFactory 对象来创建session
//工具类提供一个创建session的方法
sessionFactory=HibernateUtil.getSessionFactory();
}
//增加;
@Test
public void testInsert(){
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
StudentClass sc=new StudentClass();
sc.setName("大数据0302");
session.save(sc);
Student s=new Student();
s.setName("link");
s.setStudentClass(sc);
session.save(s);
tx.commit();
session.close();
}
}
5.程序之后我们打开数据库: