giliermo
giliermo

Reputation: 161

Hard time understanding relationship data storing using JPA (spring boot)

I want to know how to store entity in database without storing it's relative as well.

for example you have jobs for workers in your company and you want to save new jobs into your database.

you create 2 entities Job and Worker with OneToMany relationship ( 1 job for 3 or more workers )

when you save job into database it has field : workers and it must not be null.

Problem : when you save job into database it's workers are saved too ! ( jobRepository.save(myJob)

so every time i add new job workers who are already in my database are being added again ( and it breaks application of course because you can not have duplicate workers)

How can i fix this problem? thanks !

example : Job

@Entity
@Table(name = "job")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Job{

  @Id
  @Column(name = "id")
  private Long id;


  @OneToMany(mappedBy = "job", fetch = FetchType.EAGER)
  private Set<Worker> workers;
}

example : Worker

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "workers")
public class User extends DataAudit {

  @Id
  private Long id;


  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "job_id", referencedColumnName = "id")
  private Job job;

}

example : saving job in database

Worker worker1 = workerService.getWorkerById(1);
Job job = new Job(1,worker1)

jobRepository.save(job)

gives me an error ----> JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation

Upvotes: 0

Views: 93

Answers (1)

oat
oat

Reputation: 72

To avoid duplicated ids add @GeneratedValue(strategy = GenerationType.AUTO) on the id field.

Good luck

Upvotes: 1

Related Questions