I'm using Hibernate and Java to implement a database.
I have created the following two annotations:
@Entity public class Cargo implements Serializable{
@Id
@GeneratedValue
private Long id;
private String cargo;
@OneToOne(mappedBy="cargo")
private Funcionario funcionario;
}
and
@Entity public class Funcionario implements Serializable{
@Id @GeneratedValue private Long id;
private String nome;
private String sexo;
private String telefone;
@OneToOne
private Cargo cargo;
}
Then I try to insert data with the following code:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("BD04PU");
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
Cargo novoCargo = new Cargo();
Funcionario novoFuncionario = new Funcionario();
Scanner entrada = new Scanner(System.in);
System.out.print("\nCargo: ");
novoCargo.setCargo(entrada.nextLine());
manager.persist(novoCargo);
System.out.print("\nNome: ");
novoFuncionario.setNome(entrada.nextLine());
System.out.print("\nSexo: ");
novoFuncionario.setSexo(entrada.nextLine());
System.out.print("\nTelefone: ");
novoFuncionario.setTelefone(entrada.nextLine());
novoFuncionario.setCargo(novoCargo);
manager.persist(novoFuncionario);
manager.getTransaction().commit();
factory.close();
but as the result the foreign keys of Cargo and Funcionario count as follows: Cargo starts with 1 whereas Funcionario starts with 2, then Cargo primary key becomes 3 and Funcionario primary key becomes 4.
It is as if both primary keys were the same.
Why is that so? How to fix it?
Above, the Cargo id should be used as a foreign key in the Funcionario table.