jpa
Mapping molti a uno
Ricerca…
Parametri
| Colonna | Colonna |
|---|---|
| @TableGenerator | Utilizza la strategia del generatore di tabelle per la creazione automatica dell'ID |
| @GeneratedValue | Specifica che il valore applicato ai campi è un valore generato |
| @id | Annota il campo come identificatore |
| @ManyToOne | Specifica la relazione Molti a uno tra Dipendente e Reparto. Questa annotazione è contrassegnata da più parti. vale a dire che più dipendenti appartengono a un singolo dipartimento. Quindi Department è annotato con @ManyToOne nell'entità Employee. |
| @JoinColumn | Specifica la colonna della tabella del database che memorizza la chiave esterna per l'entità correlata |
Dipendente del dipartimento ManyToOne
Entità dei dipendenti
@Entity
public class Employee {
@TableGenerator(name = "employee_gen", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_val", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "employee_gen")
private int idemployee;
private String firstname;
private String lastname;
private String email;
@ManyToOne
@JoinColumn(name = "iddepartment")
private Department department;
// getters and setters
// toString implementation
}
Dipartimento Entità
@Entity
public class Department {
@Id
private int iddepartment;
private String name;
// getters, setters and toString()
}
Classe di prova
public class Test {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPAExamples");
EntityManager em = emf.createEntityManager();
EntityTransaction txn = em.getTransaction();
Employee employee = new Employee();
employee.setEmail("[email protected]");
employee.setFirstname("Prasad");
employee.setLastname("kharkar");
txn.begin();
Department department = em.find(Department.class, 1);//returns the department named vert
System.out.println(department);
txn.commit();
employee.setDepartment(department);
txn.begin();
em.persist(employee);
txn.commit();
}
}
Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow