hibernate onetomany 双向

建表语句:

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=3 DEFAULT 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=6 DEFAULT 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
@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 = FetchType.LAZY,延迟加载策略,如果不想延迟加载可以用FetchType.EAGER
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @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) {
        this.company = company;
    }
}
Company.java
@Entity
@Table(name = "t_company")
public class Company {

    private Integer companyId;
    private String  companyName;
    private Set<Employee> employees;
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getCompanyId() {
        return companyId;
    }
    /**
     * @OneToMany 与 OneToOne相似的也用mappedBy,参考了Employee
     * 
     */
    @OneToMany(mappedBy = "company",cascade=CascadeType.ALL)
    public Set<Employee> getEmployees() {
        return employees;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public void setEmployees(Set<Employee> employees) {
        this.employees = employees;
    }
}

相关推荐