我对hibernate和spring非常新,并且无法理解如何在表之间建立关系。我需要存储业务伙伴机器关系数据。即一个业务合作伙伴拥有多台机器,但单台机器只有一个业务合作伙伴。下面我提到了表格信息和我的代码。请帮助我,提前帮助谢谢。
##################业务合作伙伴表####################
CREATE TABLE `bp_master` (
`BPId` int(11) NOT NULL,
`BPName` varchar(100) DEFAULT NULL,
`BPPrimaryAddress` varchar(45) DEFAULT NULL,
`BPSecondaryAddress` varchar(45) DEFAULT NULL,
`BPPrimaryPhoneNum` varchar(45) DEFAULT NULL,
`BPSecondaryPhoneNum` varchar(45) DEFAULT NULL,
`BPContactName1` varchar(45) DEFAULT NULL,
`BPContantName2` varchar(45) DEFAULT NULL,
`BPContactName3` varchar(45) DEFAULT NULL,
`BPPrimaryAdminId` varchar(45) NOT NULL,
`BPStatus` varchar(45) DEFAULT NULL,
`BPTypeId` int(11) DEFAULT NULL,
`BPStatusChangeTimeStamp` datetime DEFAULT NULL,
PRIMARY KEY (`BPId`),
KEY `BPType_idx` (`BPTypeId`),
CONSTRAINT `BPType` FOREIGN KEY (`BPTypeId`) REFERENCES `bp_type_master`
(`BPTypeId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
###############机床表######################
CREATE TABLE `machine_master` (
`MachineId` int(11) NOT NULL,
`MachineName` varchar(45) DEFAULT NULL,
`MachineLocation` varchar(45) NOT NULL,
`MachineAddress` varchar(45) NOT NULL,
`MachineInstalledDate` datetime DEFAULT NULL,
`MachineStatus` varchar(45) DEFAULT NULL,
`MachineStatusChangeTimeStamp` datetime DEFAULT NULL,
`MachineTypeId` varchar(45) DEFAULT NULL,
PRIMARY KEY (`MachineId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
################## bp_machine_rel table ####################
CREATE TABLE `bp_machine_rel` (
`BPId` int(11) DEFAULT NULL,
`MachineId` int(11) DEFAULT NULL,
`BPMachineStatus` varchar(45) DEFAULT NULL,
`BPMachineStatusChangeTimeStamp` datetime DEFAULT NULL,
UNIQUE KEY `MachineId_UNIQUE` (`MachineId`),
KEY `BPId_idx` (`BPId`),
KEY `MachineId_idx` (`MachineId`),
CONSTRAINT `BPId` FOREIGN KEY (`BPId`) REFERENCES `bp_master` (`BPId`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `MachineId` FOREIGN KEY (`MachineId`) REFERENCES
`machine_master` (`MachineId`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
class Machine(){
@OneToOne
private BusinessPartner bp;
}
class BusinessPartner{
@OneToMany
private List<Machine> bpMachines;
}
答案 0 :(得分:0)
正如您所描述的那样:一个业务合作伙伴拥有许多计算机。所以很多拥有一个业务合作伙伴(如果您想要双向关系)。
@Entity
public class BusinessPartner{
@OneToMany
@JoinColumn(name="fk_machine") //machine foreign key is the BusinessPartner table
private List<Machine> bpMachines;
}
@Entity
public class Machine(){
@ManyToOne
private BusinessPartner bp;
}