Phil
Phil

Reputation: 87

Spring Data Rest save record with relation (foreign-key) in Java (repo.save())

I don't know how to save a record in SDR with a link to an existing table. For example:

There is a lookup-table Flag and another table Account with name and n:1 relation to Flag-ID. The IDs in Flag-table are already created.

@Entity
public class Account{
    public Account(String name, Flag flag){
        this.name = name;
        this.flag = flag;
    }

    @Id
    private int id;

    @Column
    private String name;

    @ManyToOne
    private Flag flag;
    // Getter & Setter
}

@Entity
public class Flag{
    public Flag(String title){
        this.title = title;
    }

    @Id
    private int id;

    @Column
    private String title;
    // Getter & Setter
}

Now I want to add an account and link it to the flag-id like this:

AccountRepo accountRepo;
accountRepo.save(new Account("Name", 0));

But I declared an object in my account-function and if I want to execute the save-function, I have to add a flag-object like this:

accountRepo.save(new Account("Name", new Flag("title")));

However in this case, the framework will add a new Flag-record, what I don't want. I only want to link it.

So I need help for solving my problem.

Thanks!

Edit: The two answers from @piotr-sołtysiak and @upesh-m helped and worked for me. Thanks for your help!

Upvotes: 1

Views: 912

Answers (2)

Upesh M
Upesh M

Reputation: 402

You can use 'merge' of hibernate, ie. entityManager.merge(new Account("Name", new Flag("title"))). But the Id of the Flag should be an existing Id , so that it just adds an entry to Account.

ie. If you already have a flag record existing in db with id = 1, and you want to add an account linked to this flag, then use entityManager.merge(new Account("Name", existingFlagObject)

Upvotes: 2

Piotr Sołtysiak
Piotr Sołtysiak

Reputation: 1006

  1. Find desired flag entity using dedicated repository, e.g

    Flag flag = flagRespository.findByTitle("title");
    
  2. Set it in Account entity and save:

    accountRepo.save(new Account("Name", flag));
    

Upvotes: 2

Related Questions