java - @OneToMany is not fetching for existing childs
问题描述
I have code to archieve @ManyToOne
relation using Hibernate. I have two classes Package
and Address
. In Address
i would like to have unique entries where every address is somehow different from other. Then I have Package
which is using it.
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Long id;
String street_with_number;
String city;
String region;
//...
}
@Entity
public class Package {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Long id;
String eshopId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="destination_address_id")
private Address destination_address;
//...
}
Then I have JpaRepository to create repo:
@RepositoryRestResource
public interface PackageRepository extends JpaRepository<Package, Long> {
//...
}
Afterwards I am using it injected in REST controller
@RestController
@RequestMapping("/api/")
public class RestController {
private PackageRepository packageRepository;
@Inject
public void setRepository(PackageRepository packageRepository) {
this.packageRepository = packageRepository;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> addPack(@RequestBody Package pack) {
return new ResponseEntity<>(packageRepository.save(pack), HttpStatus.CREATED);
}
}
Then using HTTP REST I send json like this
{
"eshopId" : 1,
"destination_address": {
"street_with_number": "string",
"city": "string",
"region": "string"
}
}
Which creates one entry in table Package
and one in Address with OK also destination_address_id pointing to right Address.id
. Then I send the same JSON again and hibernate creates new Address
same as that one before, it is not reusing it.
I would like hibernate to check if address exists and if yes, it would not create new row in table Address
but use that one which is already there. Is that somehow simply possible? This behavior creates two duplicate lines (only ID is different) which is not what I want. Thanks for any help!
解决方案
您必须检查此地址是否已由您自己定义。没有 Hibernate 机制可以为您做到这一点。
我建议您创建一个AddressService
with 方法,让我们说一个getOrCreate()
方法,该方法将检查是否存在带有传递数据的地址或者是否应该创建它。这对您来说是某种业务规则,因此在控制器和存储库之间提供一个额外的层感觉是个好主意。
推荐阅读
- c# - NET CORE 3.1 OpenIdConnect 重定向
- angular - 角度延迟加载
- javascript - React Hooks - 更改父样式以反映子 onClick
- javascript - React Native 无法 npx 初始化项目,找不到模块错误
- bash - 使用 bash 脚本暴力破解我的在线帐户密码
- c# - 等待 CefSharp 中的 javascript 渲染页面加载
- python-3.x - 通过 python 进行的弹性搜索给出了错误的计数
- python - 在 Python 中将值插入二叉树
- r - 将闪亮与 facet_grid 相结合
- python - 如果每个子数组都包含字符串,则数组数组是否与数组数组相同?