hibernate注解
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
环境:
Hibernate 3.3.1
Maven 3.0.4
MySQL 5.5.13
Myeclipse 8.6.1
建表语句:
DROP TABLE IF EXISTS `t_company`;
CREATE TABLE `t_company` (
`companyId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`companyName` varchar(30) NOT NULL,
PRIMARY KEY (`companyId`)
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULT CHARSET=gb2312;
INSERT INTO `t_company` VALUES ('1', 'Sun');
INSERT INTO `t_company` VALUES ('2', 'Apache');
DROP TABLE IF EXISTS `t_employee`;
CREATE TABLE `t_employee` (
`employeeId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`employeeName` varchar(15) NOT NULL,
`cid` int(10) unsigned NOT NULL,
PRIMARY KEY (`employeeId`)
) ENGINE=InnoDB AUTO_INCREMENT=6DEFAULT CHARSET=gb2312;
INSERT INTO `t_employee` VALUES ('1', 'Tom', '1');
INSERT INTO `t_employee` VALUES ('2', 'Summ', '1');
INSERT INTO `t_employee` VALUES ('3', 'Cat', '2');
INSERT INTO `t_employee` VALUES ('4', 'Vinylon', '1');
INSERT INTO `t_employee` VALUES ('5', 'Dog', '2');
目录结构:
Employee.java
package com.fancy.po;
import javax.persistence.CascadeType; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/*** -----------------------------------------
* @文件: Employee.java
* @作者: fancy
* @邮箱: fancyzero@
* @时间: 2012-6-10
* @描述: 实体类
* -----------------------------------------
*/
/*** 下面只说@ManyToOne,如需了解其他注解,
* 可以参考上一篇:/fancyzero/archive/2012/06/10/hibernate-one-t o-one-annotation.html
*/@Entity
@Table(name = "t_employee")
public class Employee {
private Integer employeeId;
private String employeeName;
private Company company;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getEmployeeId() {
return employeeId;
}
/*** @ManyToOne:多对一,cascade:级联,请参考上一篇
* fetch = ZY,延迟加载策略,如果不想延迟加载可以用FetchType.EAGER
*/@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH},fetch = ZY) @JoinColumn(name = "cid")
public Company getCompany() {
return company;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public void setCompany(Company company) {