0

I'm facing the following problem: I have one table A and B with a foreign key to table A. An entity has the following field: A:

public class A{

    @Column(name = "id_adres", nullable = false)
    private Long idAddress;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id_adres", nullable = false)
    private Long idAddress;

B entity has a field (among others):

public class B{
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name = "id_adres", nullable = false)
    private Long idAddress;
    @Column(name = "id_adres", nullable = false)
    private Long idAddress;

How to add the field of type B to A entity? A:

@OneToOne(mappedBy = "idAddress")
private B b

This solution doesn't work, field B b in A entity is NULL after the query statement.

i.karayel
  • 4,377
  • 2
  • 23
  • 27
Matley
  • 1,953
  • 4
  • 35
  • 73
  • 1
    Possible duplicate of [JPA Hibernate One-to-One relationship](https://stackoverflow.com/questions/787698/jpa-hibernate-one-to-one-relationship) – i.karayel Mar 01 '19 at 11:25
  • Unfortunately doesn't work with OneToOne @PrimaryKeyJoinColumn - maybe because I have Long instead of a object type in B entity – Matley Mar 01 '19 at 11:38

1 Answers1

2

the long is not the reason I have the same example with long try like this:

public class UserToken {
    @OneToOne(targetEntity = User.class)
    @JoinColumn(nullable = false, name = "user_id")
    private long tokenId;

}

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id", unique = true, nullable = false)
    private long userId;

}
i.karayel
  • 4,377
  • 2
  • 23
  • 27
  • And your entity (table) UserToken doesn't have foreign key to the User? – Matley Mar 01 '19 at 13:19
  • Yes, you don't need to put the foreign key for the user. There are many ways you can use one of for oneToOne like https://www.baeldung.com/jpa-join-column – i.karayel Mar 01 '19 at 13:30
  • Doesn't work - maybe the problem is that I use query: address = em.createQuery("SELECT b FROM Address b WHERE... – Matley Mar 01 '19 at 13:31
  • 1
    Query query = em.createQuery("SELECT a FROM Address a WHERE a.filedName= :filedName"); query.setParameter("filedName", value); and query.getResultList(); – i.karayel Mar 01 '19 at 13:54
  • and JOIN? There is not foreign key on table Address (A) to the B property so maybe should I use JOIN? SELECT a FROM Address a JOIN a.addressProperty ap ON ap.idAddress = a.idAddress WHERE a.idClient=:id") – Matley Mar 01 '19 at 14:08
  • 1
    em.createQuery("SELECT b FROM Address b left JOIN b.addressProperty ap WHERE b.idClient=:id").setParameter("id", idClient).getResultList(); WORKS! Thank you @ikarayel! – Matley Mar 01 '19 at 15:01
  • I found the following BUG - probably its my case! https://hibernate.atlassian.net/browse/HHH-7307 – Matley Mar 02 '19 at 14:45