Estoy haciendo una aplicacion en Java y para crear la interfaz grafica he empleado Scene Builder.
Mi aplicacion almacena empleados. Los botones nuevo, editar y borrar hacen su funcion. Pero guardan los cambios en un fichero XML y lo que quiero yo es que conecte con una base de datos y guarde esos cambios en esa base de datos insertando, modificando o borrando las personas en la aplicacion (usando hibernate).
A continuacion dejo el codigo de algunas de las clases:
bundle controlador.vista;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.management.Alert;
import javafx.scene.management.Alert.AlertType;
import javafx.scene.management.Label;
import javafx.scene.management.TableColumn;
import javafx.scene.management.TableView;
import javafx.scene.management.TextField;
import controlador.MainApp;
import controlador.modelo.Persona;
import controlador.util.Fecha;
public class PersonaOverviewController {
@FXML
personal TableView<Persona> personTable;
@FXML
personal TableColumn<Persona, String> firstNameColumn;
@FXML
personal TableColumn<Persona, String> lastNameColumn;
@FXML
personal Label firstNameLabel;
@FXML
personal Label lastNameLabel;
@FXML
personal Label hireDateLabel;
@FXML
personal Label dniLabel;
@FXML
personal Label diasLabel;
@FXML
personal TextField buscar;
// Reference to the principle utility.
personal MainApp mainApp;
/**
* The constructor.
* The constructor is named earlier than the initialize() technique.
*/
public PersonaOverviewController() {
}
/**
* Initializes the controller class. This technique is mechanically referred to as
* after the fxml file has been loaded.
*/
@FXML
personal void initialize() {
// Initialize the individual desk with the 2 columns.
firstNameColumn.setCellValueFactory(
cellData -> cellData.getValue().firstNameProperty());
lastNameColumn.setCellValueFactory(
cellData -> cellData.getValue().lastNameProperty());
// Clear individual particulars.
showPersonDetails(null);
// Hear for choice adjustments and present the individual particulars when modified.
personTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> showPersonDetails(newValue));
}
/**
* Is known as by the principle utility to present a reference again to itself.
*
* @param mainApp
*/
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
// Add observable listing knowledge to the desk
personTable.setItems(mainApp.getPersonData());
}
/**
* Fills all textual content fields to indicate particulars concerning the individual.
* If the desired individual is null, all textual content fields are cleared.
*
* @param persona the individual or null
*/
personal void showPersonDetails(Persona persona) {
if (persona != null) {
// Fill the labels with data from the individual object.
firstNameLabel.setText(persona.getFirstName());
lastNameLabel.setText(persona.getLastName());
hireDateLabel.setText(Fecha.format(persona.getHireDate()));
dniLabel.setText(persona.getDni());
persona.diasVacaciones();
diasLabel.setText(Double.toString(persona.getDias()));
} else {
// Individual is null, take away all of the textual content.
firstNameLabel.setText("");
lastNameLabel.setText("");
hireDateLabel.setText("");
dniLabel.setText("");
diasLabel.setText("");
}
}
/**
* Referred to as when the consumer clicks the brand new button. Opens a dialog to edit
* particulars for a brand new individual.
*/
@FXML
personal void handleNewPerson() {
Persona tempPerson = new Persona();
boolean okClicked = mainApp.showPersonEditDialog(tempPerson);
if (okClicked) {
mainApp.getPersonData().add(tempPerson);
}
}
/**
* Referred to as when the consumer clicks the edit button. Opens a dialog to edit
* particulars for the chosen individual.
*/
@FXML
personal void handleEditPerson() {
Persona selectedPerson = personTable.getSelectionModel().getSelectedItem();
if (selectedPerson != null) {
boolean okClicked = mainApp.showPersonEditDialog(selectedPerson);
if (okClicked) {
showPersonDetails(selectedPerson);
/*SessionFactory manufacturing unit = HibernateUtils.getSessionFactory();
Session session = manufacturing unit.openSession();
session.getTransaction().start();
session.replace(selectedPerson);
session.getTransaction().commit();*/
}
} else {
// Nothing chosen.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("Sin selección");
alert.setHeaderText("Sin persona seleccionada");
alert.setContentText("Por favor, selecciona una persona de la tabla.");
alert.showAndWait();
}
}
/**
* Referred to as when the consumer clicks on the delete button.
*/
@FXML
personal void handleDeletePerson() {
int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
personTable.getItems().take away(selectedIndex);
} else {
// Nothing chosen.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("Error de selecion");
alert.setHeaderText("No se ha seleccionado ningun registro");
alert.setContentText("Por favor, seleccione una persona de la tabla.");
alert.showAndWait();
}
}
@FXML
personal void handleGastarVacaciones() {
Persona selectedPerson = personTable.getSelectionModel().getSelectedItem();
if (selectedPerson != null) {
boolean okClicked = mainApp.showPersonDiasDialog(selectedPerson);
if (okClicked) {
showPersonDetails(selectedPerson);
}
} else {
// Nothing chosen.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("Sin selección");
alert.setHeaderText("Sin persona seleccionada");
alert.setContentText("Por favor, selecciona una persona de la tabla.");
alert.showAndWait();
}
}
@FXML
personal void buscarDatos() {
personTable.setItems(mainApp.getPersonData());
FilteredList<Persona> filteredData = new FilteredList<>(mainApp.getPersonData(), p -> true);
buscar.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(individual -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String filtroMinuscula = newValue.toLowerCase();
if (individual.getFirstName().toLowerCase().indexOf(filtroMinuscula) != -1){
return true;
}else if (individual.getLastName().toLowerCase().indexOf(filtroMinuscula) != -1){
return true;
}else if (individual.getDni().toLowerCase().indexOf(filtroMinuscula) != -1){
return true;
}else
return false;
});
});
SortedList<Persona> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(personTable.comparatorProperty());
personTable.setItems(sortedData);
}
}
Entiendo que en los botones nuevo, editar y borrar tengo que implementar esa modificacion de la base de datos con un codigo tipo:
SessionFactory manufacturing unit = HibernateUtils.getSessionFactory();
Session session = manufacturing unit.openSession();
session.getTransaction().start();
session.delete();
session.getTransaction().commit();
He conseguido introducir en la base de datos algunas ocurrencias de Persona pero lo hago al inicializar la app, para que ésta tenga algún contenido al iniciarse, pero lo que quiero es que los cambios de nuevo, editar y borrar tengan repercusión en la BBDD pero no doy con la tecla de como hacerlo, alguien me puede ayudar?
Muchas gracias! Si es necesario puedo colgar mas codigo si sirve de ayuda.