I'm starting to study jpa now and I have a question about the concept of owner and non-owner, according to an article I read, the non-owner will be every attribute that doesn't have mappedBy, but when there is a bidirectional relationship, without the mappedBy notation, I am not sure if there is an owner of a relationship, I also noticed that the mappedBy option only appears when it is @OneToMany and not @ManyToOne, that is, what really defines the owner of the relationship and how it affects in practice
initial data which is loaded every time when running the application
Sql
insert into client (id, name) values (null, 'Marina');
insert into client (id, name) values (null, 'Joana');
insert into demand(id, name) values(null, "Banana");
insert into demand(id, name) values(null, "Apple");
insert into demand(id, name) values(null, "jabuticaba");
Demand.java
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "demand")
public class Demand {
@Id
@EqualsAndHashCode.Include
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Client client;
private String name;
}
Client.java
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "client")
public class Client {
@EqualsAndHashCode.Include
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany
private List<Demand> demand;
}
Main.java
public class Main {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("unit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Client client = entityManager.find(Client.class, 1);
Demand demand1 = entityManager.find(Demand.class, 1);
Demand demand2 = entityManager.find(Demand.class, 2);
Demand demand3 = entityManager.find(Demand.class, 3);
entityManager.getTransaction().begin();
client.setDemand(Arrays.asList(demand1, demand2, demand3));
entityManager.getTransaction().commit();
client = entityManager.find(Client.class, 1);
System.out.println("Client name: " + client.getName() + " Demand name " +
client.getDemand().get(0).getName());
System.out.println("Client name: " + client.getName() + " Demand name " +
client.getDemand().get(1).getName());
}
}
My final question is, who is the owner of the relation, since I didn't use mappeBy ? Another thing, I noticed that it creates an intermediate table, when I don't use mappedBy, if anyone can give me many details on how mappedBy works, I would be very grateful.