CREATE TABLE tb_class
(
id bigint NOT NULL auto_increment COMMENT ‘ID‘,
no varchar(10) NOT NULL COMMENT ‘班级编号‘,
name varchar(50) NOT NULL COMMENT ‘班级名称‘,
PRIMARY KEY (id)
) COMMENT ‘班级信息表‘;
CREATE TABLE tb_student
(
id bigint NOT NULL auto_increment COMMENT ‘ID‘,
no varchar(10) NOT NULL COMMENT ‘学号‘,
name varchar(50) NOT NULL COMMENT ‘姓名‘,
sex char(1) NOT NULL COMMENT ‘性别‘,
birthday datetime COMMENT ‘出生日期‘,
class_id bigint NOT NULL COMMENT ‘班级ID‘,
PRIMARY KEY (id)
) COMMENT = ‘学生信息表‘;
ALTER TABLE tb_student ADD CONSTRAINT fk_tb_student_tb_class_1 FOREIGN KEY (class_id) REFERENCES tb_class (id);
package model;
public class ClassInfo
{
private Long id;
private String no;
private String name;
private List<Student> students = new ArrayList<Student>();
//省略setter、getter、toString...
}
package model;
import java.sql.Date;
public class Student
{
private Long id;
private String no;
private String name;
private String sex;
private Date birthday;
private ClassInfo classInfo;
//省略setter、getter、toString...
}
- <hibernate-mapping package="model">
<class name="ClassInfo" table="tb_class">
<id name="id">
<generator class="native"></generator>
</id>
<property name="no" column="no"/>
<property name="name" column="name"/>
</class>
</hibernate-mapping>
<hibernate-mapping package="model">
<class name="Student" table="tb_student">
<id name="id">
<generator class="native"></generator>
</id>
<property name="no" column="no"/>
<property name="name" column="name"/>
<property name="sex" column="sex"/>
<property name="birthday" column="birthday"/>
<many-to-one name="classInfo" column="class_id" class="model.ClassInfo" lazy="false"/>
</class>
</hibernate-mapping>
public static void main(String[] args)
{
Student student;
Configuration cfg = new Configuration();
cfg.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
System.out.println("连接数据库");
Session session = sf.openSession();
student=(Student) session.get(Student.class, new Long(1));
System.out.println(student);
System.out.println(student.getClassInfo());
session.close();
System.out.println("关闭数据库");
System.exit(0);
}
<hibernate-configuration>
<session-factory>
<!-- 省略其他...,设置实体类到数据库的映射文件 -->
<mapping resource="model/ClassInfo.hbm.xml"/>
<mapping resource="model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
连接数据库
Hibernate:
select
student0_.id as id1_2_0_,
student0_.no as no2_2_0_,
student0_.name as name3_2_0_,
student0_.sex as sex4_2_0_,
student0_.birthday as birthday5_2_0_,
student0_.class_id as class_id6_2_0_
from
tb_student student0_
where
student0_.id=?
Hibernate:
select
classinfo0_.id as id1_1_0_,
classinfo0_.no as no2_1_0_,
classinfo0_.name as name3_1_0_
from
tb_class classinfo0_
where
classinfo0_.id=?
Student [id=1, no=000001, name=学生1, sex=男, birthday=2015-01-27]
ClassInfo [id=22, no=000022, name=班级22]
关闭数据库
<hibernate-mapping package="model">
<class name="Student" table="tb_student">
<id name="id">
<generator class="native"></generator>
</id>
<property name="no" column="no"/>
<property name="name" column="name"/>
<property name="sex" column="sex"/>
<property name="birthday" column="birthday"/>
</class>
</hibernate-mapping>
<hibernate-mapping package="model">
<class name="ClassInfo" table="tb_class">
<id name="id">
<generator class="native"></generator>
</id>
<property name="no" column="no"/>
<property name="name" column="name"/>
<bag name="students">
<key column="class_id"/>
<one-to-many class="model.Student"/>
</bag>
</class>
</hibernate-mapping>
public static void main(String[] args)
{
ClassInfo classInfo;
Configuration cfg = new Configuration();
cfg.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
System.out.println("连接数据库");
Session session = sf.openSession();
classInfo =(ClassInfo) session.get(ClassInfo.class, new Long(1));
System.out.println(classInfo);
System.out.println(classInfo.getStudents().size());
System.out.println(classInfo.getStudents().get(0));
session.close();
System.out.println("关闭数据库");
System.exit(0);
}
连接数据库
Hibernate:
select
classinfo0_.id as id1_1_0_,
classinfo0_.no as no2_1_0_,
classinfo0_.name as name3_1_0_
from
tb_class classinfo0_
where
classinfo0_.id=?
ClassInfo [id=1, no=000001, name=班级1]
Hibernate:
select
students0_.class_id as class_id6_1_0_,
students0_.id as id1_2_0_,
students0_.id as id1_2_1_,
students0_.no as no2_2_1_,
students0_.name as name3_2_1_,
students0_.sex as sex4_2_1_,
students0_.birthday as birthday5_2_1_,
students0_.class_id as class_id6_2_1_
from
tb_student students0_
where
students0_.class_id=?
35
Student [id=24, no=000024, name=学生24, sex=女, birthday=2015-01-27]
关闭数据库
<hibernate-mapping package="model">
<class name="Student" table="tb_student">
<id name="id">
<generator class="native"></generator>
</id>
<property name="no" column="no"/>
<property name="name" column="name"/>
<property name="sex" column="sex"/>
<property name="birthday" column="birthday"/>
<many-to-one name="classInfo" column="class_id" class="model.ClassInfo" lazy="false"/>
</class>
</hibernate-mapping>
<hibernate-mapping package="model">
<class name="ClassInfo" table="tb_class">
<id name="id">
<generator class="native"></generator>
</id>
<property name="no" column="no"/>
<property name="name" column="name"/>
<bag name="students" inverse="false" cascade="none" lazy="false">
<key column="class_id"/>
<one-to-many class="model.Student"/>
</bag>
</class>
</hibernate-mapping>
public static void main(String[] args)
{
Student student;
Configuration cfg = new Configuration();
cfg.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
System.out.println("连接数据库");
Session session = sf.openSession();
student=(Student) session.get(Student.class, new Long(1));
System.out.println(student);
System.out.println(student.getClassInfo());
System.out.println(student.getClassInfo().getStudents().size());
session.close();
System.out.println("关闭数据库");
System.exit(0);
}
连接数据库
Hibernate:
select
student0_.id as id1_2_0_,
student0_.no as no2_2_0_,
student0_.name as name3_2_0_,
student0_.sex as sex4_2_0_,
student0_.birthday as birthday5_2_0_,
student0_.class_id as class_id6_2_0_
from
tb_student student0_
where
student0_.id=?
Hibernate:
select
classinfo0_.id as id1_1_0_,
classinfo0_.no as no2_1_0_,
classinfo0_.name as name3_1_0_
from
tb_class classinfo0_
where
classinfo0_.id=?
Hibernate:
select
students0_.class_id as class_id6_1_0_,
students0_.id as id1_2_0_,
students0_.id as id1_2_1_,
students0_.no as no2_2_1_,
students0_.name as name3_2_1_,
students0_.sex as sex4_2_1_,
students0_.birthday as birthday5_2_1_,
students0_.class_id as class_id6_2_1_
from
tb_student students0_
where
students0_.class_id=?
Student [id=1, no=000001, name=学生1, sex=男, birthday=2015-01-27]
ClassInfo [id=22, no=000022, name=班级22]
38
关闭数据库
public static void main(String[] args)
{
ClassInfo classInfoNew;
ClassInfo classInfo;
Student studentNew;
Student student;
Configuration cfg = new Configuration();
cfg.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
System.out.println("连接数据库");
Session session = sf.openSession();
Transaction transaction = session.beginTransaction();
try
{
classInfoNew = new ClassInfo();
classInfoNew.setName("测试Class");
classInfoNew.setNo("000");
studentNew = new Student();
studentNew.setName("测试Student");
studentNew.setNo("000");
studentNew.setSex("男");
studentNew.setBirthday(new Date(1993, 6, 11));
classInfoNew.getStudents().add(studentNew);
studentNew.setClassInfo(classInfoNew);
session.save(classInfoNew);//一定要先保存classInfo不然会报错,因为数据库约束了class_id为NOT NULL
session.save(studentNew);
student = (Student) session.get(Student.class, new Long(1));
student.setClassInfo(classInfoNew);//执行update维护关系
classInfoNew.getStudents().add(student);//执行update维护关系,update语句数受关联对象数影响,此处的update会有重复!
transaction.commit();
}
catch (Exception e)
{
transaction.rollback();
System.out.println("错误:" + e);
}
finally
{
session.close();
System.out.println("关闭数据库");
}
System.exit(0);
}
连接数据库
Hibernate:
insert
into
tb_class
(no, name)
values
(?, ?)
Hibernate:
insert
into
tb_student
(no, name, sex, birthday, class_id)
values
(?, ?, ?, ?, ?)
Hibernate:
- ........ 省略若干获取关联对象的查询语句
Hibernate:
update
tb_student
set
no=?,
name=?,
sex=?,
birthday=?,
class_id=?
where
id=?
Hibernate:
update
tb_student
set
class_id=?
where
id=?
Hibernate:
update
tb_student
set
class_id=?
where
id=?
关闭数据库
- <bag name="students" lazy="false" inverse="true">
<key column="class_id"/>
<one-to-many class="model.Student"/>
</bag>
Hibernate:
update
tb_student
set
no=?,
name=?,
sex=?,
birthday=?,
class_id=?
where
id=?
- <many-to-one name="classInfo" column="class_id" class="model.ClassInfo" lazy="false" cascade="save-update"/>
连接数据库
Hibernate:
insert
into
tb_class
(no, name)
values
(?, ?)
Hibernate:
insert
into
tb_student
(no, name, sex, birthday, class_id)
values
(?, ?, ?, ?, ?)
关闭数据库
<bag name="students" lazy="false" inverse="true" cascade="delete">
<key column="class_id"/>
<one-to-many class="model.Student" />
</bag>
Hibernate:
delete
from
tb_student
where
id=?
Hibernate:
delete
from
tb_class
where
id=?
<bag name="students" lazy="false" inverse="true" cascade="all-delete-orphan">
<key column="class_id"/>
<one-to-many class="model.Student" />
</bag>
CREATE TABLE tb_area
(
id bigint NOT NULL auto_increment COMMENT ‘ID‘,
name varchar(50) NOT NULL COMMENT ‘地区名称‘,
parent_id bigint COMMENT ‘所属区域ID‘,
PRIMARY KEY (id)
) COMMENT = ‘区域信息表‘;
-- 外键约束可续选
ALTER TABLE tb_area ADD CONSTRAINT fk_tb_area_1 FOREIGN KEY (parent_id) REFERENCES tb_area (id);
package model;
import java.util.Set;
public class Area
{
private Long id;
private String name;
private Area parentArea;
private Set<Area> childAreas = new HashSet<Area>();
// 省略setter、getter、toString...
}
<hibernate-mapping package="model">
<class name="Area" table="tb_area">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"/>
<many-to-one name="parentArea" column="parent_id" class="model.Area" cascade="save-update"/>
<set name="childAreas" inverse="true">
<key column="parent_id"/>
<one-to-many class="model.Area"/>
</set>
</class>
</hibernate-mapping>
public static void main(String[] args)
{
Configuration cfg = new Configuration();
cfg.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
System.out.println("连接数据库");
Session session = sf.openSession();
Transaction transaction = session.beginTransaction();
try
{
Area area1=new Area();
Area area2=new Area();
Area area3=new Area();
Area area4=new Area();
Area area5=new Area();
area1.setName("中国");
area2.setName("湖北省");
area3.setName("湖南省");
area4.setName("武汉市");
area5.setName("仙桃市");
area2.setParentArea(area1);
area3.setParentArea(area1);
area4.setParentArea(area2);
area5.setParentArea(area2);
session.save(area3);
session.save(area4);
session.save(area5);
transaction.commit();
}
catch (Exception e)
{
transaction.rollback();
System.out.println("错误:" + e);
}
finally
{
session.close();
System.out.println("关闭数据库");
}
System.exit(0);
}
连接数据库
Hibernate: insert into tb_area (name, parent_id) values (?, ?)
Hibernate: insert into tb_area (name, parent_id) values (?, ?)
Hibernate: insert into tb_area (name, parent_id) values (?, ?)
Hibernate: insert into tb_area (name, parent_id) values (?, ?)
Hibernate: insert into tb_area (name, parent_id) values (?, ?)
关闭数据库
area1.setName("中国");
area2.setName("湖北省");
area2.setParentArea(area1);
area1.getChildAreas().add(area2);
public Area addChildArea(Area area)
{
if (area != null)
{
if (this.childAreas == null)
{
this.childAreas = new HashSet<Area>();
}
//删除原有的关系
if (area.getParentArea() != null)
{
area.getParentArea().getChildAreas().remove(area);
}
//设置当前关系
this.childAreas.add(area);
area.setParentArea(this);
}
return this;
}
area1.setName("中国");
area2.setName("湖北省");
area3.setName("湖南省");
area1.addChildArea(area2).addChildArea(area3);
<many-to-one name="PropertyName"
access="field|property"
column="TableColumn"
class="ClassName"
property-ref="PropertyNameFromAssociatedClass"
foreign-key="foreign-key"
formula="arbitrary SQL expression"
update="true|false"
insert="true|false"
not-null="true|false"
unique="true|false"
unique-key="unique-key"
index="index_name"
not-found="exception|ignore"
outer-join="true|false"
fetch="join|select"
lazy="true|false"
cascade="all|none|save-update|delete"
optimistic-lock="true|false"
embed-xml="true|false"
entity-name="EntityName"
node="element-name"/>
<bag name="EntityClassName"
access="field|property|ClassName"
collection-type="collection-type"
schema="schema"
catalog="catalog"
check="arbitrary sql check condition"
table="TableName"
subselect="SQL expression"
where="arbitrary sql where condition"
optimistic-lock="false|true"
inverse="false|true"
fetch="join|select"
batch-size="5"
cascade="all|none|save-update|delete"
lazy="false|true"
mutable="false|true"
outer-join="false|true"
order-by="arbitrary sql order by condition"
embed-xml="false|true"
persister="PersisterClass"
node="element-name"/>
<one-to-many class="ClassName"
not-found="exception|ignore"
embed-xml="true|false"
entity-name="EntityName"
node="element-name" />
原文:http://www.cnblogs.com/LiZhiW/p/4277030.html