首页 > 解决方案 > @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!

标签: javaspringhibernaterestspring-boot

解决方案


您必须检查此地址是否已由您自己定义。没有 Hibernate 机制可以为您做到这一点。

我建议您创建一个AddressServicewith 方法,让我们说一个getOrCreate() 方法,该方法将检查是否存在带有传递数据的地址或者是否应该创建它。这对您来说是某种业务规则,因此在控制器和存储库之间提供一个额外的层感觉是个好主意。


推荐阅读