Hibernate

作为我的Hibernate岂不参考 这个站点很帮: http://viralpatel.net/blogs/hibernate-one-to-many-xml-mapping-tutorial/

1. 首先是DB 的创建:

EMPLOYEEE<->EMPLOYEEDETAIL:  1:1的关系。 主表EMPLOYEE, Reference表EMPLOYEEDETAIL
EMPLOYEE<->DEPARTMENT: N:1多对一的关系,主表DEPARTMENT, Rererence表EMPLOYEE
EMPLOYEE<->Meeting: N:N 的关系,要引进一个新表分别对应两个ID 的组合主建
# Reference表 DEPARTMENT
CREATE TABLE `DEPARTMENT` (
  `id` bigint(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;


# Reference 表 EMPLOYEEDETAILS
CREATE TABLE `EMPLOYEEDETAILS` (
  `employee_id` bigint(10) NOT NULL AUTO_INCREMENT,
  `city` varchar(20) DEFAULT NULL,
  `road` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`employee_id`),
  CONSTRAINT `FK_EMPLOYEE` FOREIGN KEY (`employee_id`) REFERENCES `EMPLOYEE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;


CREATE TABLE `EMPLOYEE` (
  `id` bigint(10) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(20) DEFAULT NULL,
  `last_name` varchar(20) DEFAULT NULL,
  `salary` int(11) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `department_id` bigint(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_DEPT` (`department_id`),
  CONSTRAINT `FK_DEPT` FOREIGN KEY (`department_id`) REFERENCES `DEPARTMENT` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

CREATE TABLE `MEETING` (
  `meeting_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `subject` varchar(50) NOT NULL,
  `meeting_date` date NOT NULL,
  PRIMARY KEY (`meeting_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

CREATE TABLE `EMPLOYEE_MEETING` (
  `employee_id` bigint(10) NOT NULL,
  `meeting_id` bigint(20) NOT NULL,
  PRIMARY KEY (`employee_id`,`meeting_id`),
  KEY `FK_MEETING` (`meeting_id`),
  CONSTRAINT `FK_EMPLOYEES` FOREIGN KEY (`employee_id`) REFERENCES `EMPLOYEE` (`id`),
  CONSTRAINT `FK_MEETINGS` FOREIGN KEY (`meeting_id`) REFERENCES `MEETING` (`meeting_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 2. 创建xml mapping 关系:

>定义entity类

>hibernate.cfg.xml罗列所有的hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<mapping resource="Employee.hbm.xml" />
		<mapping resource="Department.hbm.xml" />
		<mapping resource="EmployeeDetail.hbm.xml" />
		<mapping resource="Meeting.hbm.xml" />

	</session-factory>
</hibernate-configuration>

 接着将OR关系写道每个hbm表中:

篇幅太常,可以参照我的github项目: https://github.com/ygshen2006/japi

posted on 2016-01-13 09:24  ygshen  阅读(161)  评论(0编辑  收藏  举报

导航