0
Hello I wanted to make a foreign key, but I don’t understand the syntax.
In the Endereco class:
@Embeddable
@Table(name = "tab_endereco")
public class Endereco {
@Column(length = 40, nullable = false)
private String logradouro;
@Column(length = 40, nullable = false)
private String bairro;
@JoinColumn(columnDefinition = "char(3)", nullable = false, foreignKey = @ForeignKey(name="fk_cidade"))
private Cidade cidade;
In the City class, where we catch the acronym:
@Entity
@Table(name = "tab_cidade")
public class Cidade {
@Id
@JoinColumn(columnDefinition = "char(3)", nullable = false, referencedColumnName = "fk_cidade")
private String sigla;
@Column(length = 40, nullable = false)
private String nome;
@Column(columnDefinition = "char(2)", nullable = false)
private Estado estado;
In class
Cidade
, the attributeestado
shouldn’t be@ManyToOne
? instead of@OneToMany
?– StatelessDev
You’re right, I made the correction.
– Gonzaga Neto
In this case, @Manytoone is saying that the many Address for a City? And how does the private City identify which attribute of the City class is the one that will serve as the foreign key? Through @Id?
– Danilo Silva
And @Joincolumn(name = "cityId"), the name inside Joincolunm has to be the same as the attribute name(private Long cityId) ?
– Danilo Silva
Hello Danilo, yes, when you do the mapping to define the relationship between the entities the API itself already makes the relationship to the primary key of the class we are linking, As to use the same name, it is not necessary, I use to keep easier reading.
– Gonzaga Neto
Danilo, has a material that is a summary of some annotations that facilitates the understanding of the use: http://www.techferry.com/articles/hibernate-jpa-annotations.html
– Gonzaga Neto