前言
在使用jpa持久化框架中,经常要建立关系表,jpa提供级联注解,这里说说其中的一对一映射关系@OneToOne关系
注解说明
@OneToOne用于映射两个实体类之间的一对一关系,比如人和身份证等关系
使用说明
实体类
建立一个设备实体类
@Data
@Entity
@FieldNameConstants
@Table(name = "sys_device")
public class SaasDevice {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String deviceName;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "saasDevice")
private SaasDeviceLoad saasDeviceLoad;
}
建立设备属性实体类
@Data
@Entity
@FieldNameConstants
@Table(name = "sys_device_load")
public class SaasDeviceLoad {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "saas_device_id", referencedColumnName = "id")
private SaasDevice saasDevice;
private Integer deviceKey;
}
备注: 外键打算建立在哪张表,就将@JoinColumn写在对应的实体类上
dao层建立
设备dao层
@Repository
public interface ISaasDeviceRepository extends JpaRepository<SaasDevice, Long>,
JpaSpecificationExecutor<SaasDevice> {
}
设备属性dao层
@Repository
public interface ISaasDeviceLoadRepository extends JpaRepository<SaasDeviceLoad, Long> {
List<SaasDeviceLoad> findBySaasDeviceIdIn(List<Long> deviceIds);
}
启动程序的时候,会建立两张映射表
外键位于对应的表
controller写法
@Slf4j
@RestController
public class TestController {
@Autowired
private ISaasDeviceRepository iSaasDeviceRepository;
@Autowired
private ISaasDeviceLoadRepository iSaasDeviceLoadRepository;
@RequestMapping("/hello")
public String hello() {
log.info("info日志====================");
SaasDevice saasDevice = new SaasDevice();
saasDevice.setDeviceName("aaa");
iSaasDeviceRepository.save(saasDevice);
SaasDeviceLoad saasDeviceLoad = new SaasDeviceLoad();
saasDeviceLoad.setDeviceKey(1);
saasDeviceLoad.setSaasDevice(saasDevice);
iSaasDeviceLoadRepository.save(saasDeviceLoad);
return "success";
}
@RequestMapping("/deleteById")
public String deleteById(@RequestParam("id") Long id) {
iSaasDeviceRepository.deleteById(id);
return "success";
}
@RequestMapping("/updateById")
public String updateById(@RequestParam("id") Long id) {
iSaasDeviceRepository.findById(id)
.ifPresent(iSaasDevice -> {
iSaasDevice.setDeviceName("aaa111");
iSaasDeviceRepository.save(iSaasDevice);
});
return "success";
}
@RequestMapping("/updateById1")
public String updateById1(@RequestParam("id") Long id) {
iSaasDeviceLoadRepository.findById(id)
.ifPresent(iSaasDeviceLoad -> {
iSaasDeviceLoad.setDeviceKey(2);
iSaasDeviceLoadRepository.save(iSaasDeviceLoad);
});
return "success";
}
}
(1)调用hello接口,会级联保存数据
(2)调用deleteById接口,会级联删除数据
(3)调用updateById接口,会更新sys_device表数据
(4)调用updateById1接口,会更新sys_device_load表数据
总结
jpa中的一对一如果相对熟悉的话,可以推荐使用,但是一般在开发过程中,因人而异,大部分不会采用外键级联表,这种根据自己技术决定