Search code examples
javahibernateapijoincolumn

JoinColumn Hibernate / API


I'm having the following problem: I want to simply join the table Markets (main) and Telephones, but I'm facing some problems while doing this with annotations.

I simply want to use the Comercio.id as the corresponding foreign key from Telefone.fk_id, but it doesn't recognize it. I also would like to ask if it's needed to create an Repository Interface for both classes.

EDIT. Also, how would look a POST req for such an example?

Comercio.java

@Entity
@Table(name = "comercio")
public class Comercio {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String cnpj;
    private String endereco;

    @OneToMany(targetEntity = Telefone.class , mappedBy = "comercio", fetch = FetchType.LAZY)
    private List<Telefone> telefones;
    private String email;

Telefone.java

@Entity
@Table(name = "telefone")
public class Telefone {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long telefone_id;

    @ManyToOne
    @JoinColumn(name="fk_id", referencedColumnName = "id")
    private Comercio comercio;
    private String telefone;

The answer I get:

{
      "nome" : "Americanas",
      "cnpj" : "000",
      "endereco" : "SQN 112",
      "telefones" : [ ],
      "email" : "contato@americanas.com",
      "comercio_id" : 1
}

Console:

Hibernate: select comercio0_.id as id1_0_, comercio0_.cnpj as cnpj2_0_, comercio0_.email as email3_0_, comercio0_.endereco as endereco4_0_, comercio0_.nome as nome5_0_ from comercio comercio0_
Hibernate: select telefones0_.fk_id as fk_id3_1_0_, telefones0_.telefone_id as telefone1_1_0_, telefones0_.telefone_id as telefone1_1_1_, telefones0_.fk_id as fk_id3_1_1_, telefones0_.telefone as telefone2_1_1_ from telefone telefones0_ where telefones0_.fk_id=**?**

Apreciate any help.


Solution

  • I would suggest that telephone is not an Entity in its own right: you will never want to query for a telefone and it only exists as part of a Comercio.

    It could then be an Embeddable rather than an entity however as it only has one property - the number - then you can simplify to the below and map it as a collection of Strings. There is then no need for a Telefone class.

    @Entity
    @Table(name = "comercio")
    public class Comercio {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String nome;
        private String cnpj;
        private String endereco;
    
        @ELementCollection
        @CollectionTable(name = "comercio_telefone", 
                    joinColumns=@JoinColumn(name="comercio_id"))
        private List<String> telefones;
    
        private String email;
    }