@joincolunm with foreignKey hibernate

0

Hello, I wanted to make a foreign key, but I do not understand the syntax.

In the Address 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 you paste 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;
    
asked by anonymous 26.05.2018 / 03:44

1 answer

2

Hello, here's an example of how you can build relationships in your classes.

Class status:

@Entity
public class Estado {

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

As for the Class City, in this class I took the liberty of placing an Id field as the primary key, I do not know if I would understand its need, however you can change according to the rules of your project:

@Entity
public class Cidade {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long cidadeId;
private String nome;

@ManyToOne
@JoinColumn(name = "estadoId")
private Estado estado;

Finally the class address, in this class I did not put the state field because the City already has a state bound to it:

public class Endereço {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String logradouro;

@ManyToOne
@JoinColumn(name = "cidadeId")
private Cidade cidade;

So let's go:

@Id = Indicates which is the unique identification attribute of the object to be persisted;

@GeneratedValue(strategy=GenerationType.IDENTITY) = When using this annotation the SGDB is responsible for generating the value of the object ID incrementally;

@ManyToOne = Defines a cardinality relation from many to one, ie Many addresses are in a single city for example;

In your code I noticed that you had used a @Embeddable annotation, in my example I took it out because this annotation is used when working with a compound key.

Thanks.

    
26.05.2018 / 13:40