How to display data from three different entities or classes in JFXTreeTableView - javafxports

I have three classes, Countries, Cities and Communities.
The Countries class relates one to many to Cities, and in Countries I have a List attribute where I store the cities. The Cities class relates from one to many to Localities, and in Cities I have a List attribute where I store the localities. My question?.
How to show in JFXTreeTableView a country like Root with its cities and the city with its communities?
Entities
#Entity
#Access(AccessType.PROPERTY)
public class GS_TablaPaises extends RecursiveTreeObject<GS_TablaPaises> implements Serializable{
# GeneratedValue ( strategy = GenerationType.TABLE , generator =
"codigoIdPais" )
# SequenceGenerator ( name = "codigoIdPais" , initialValue = 100 ,
allocationSize = 1 )
#Id
private int codigoIdPais;
private SimpleStringProperty nombrePais;
private SimpleStringProperty capitalPais;
private SimpleStringProperty dominioInternetPais;
private SimpleBooleanProperty filtrarPais;
// establecemos la relacion de uno a muchos con la tabla ciudades
#OneToMany(targetEntity = GS_TablaCiudades.class, mappedBy = "paises",
cascade = CascadeType.ALL)
private List<GS_TablaCiudades> listaCiudades = new ArrayList<
GS_TablaCiudades>();
private static final long serialVersionUID = 1L;
// constructor vacio
public GS_TablaPaises() {
super();
}
// constructor con parametros
public GS_TablaPaises(Integer codigoIdPais, String nombrePais, String
capitalPais, String dominioInternetPais, Boolean filtrarPais,
List<GS_TablaCiudades> listaCiudades) {
this.codigoIdPais = codigoIdPais;
this.nombrePais = new SimpleStringProperty(nombrePais);
this.capitalPais = new SimpleStringProperty(capitalPais);
this.filtrarPais = new SimpleBooleanProperty(filtrarPais);
this.dominioInternetPais = new SimpleStringProperty(
dominioInternetPais);
this.listaCiudades = listaCiudades;
}
.......
}
#Entity
#Access(AccessType.PROPERTY)
public class GS_TablaCiudades implements Serializable {
# GeneratedValue ( strategy = GenerationType.TABLE , generator =
"CodigoIdCiudad" )
# SequenceGenerator ( name = "CodigoIdCiudad" , initialValue = 1 ,
allocationSize = 1 )
#Id
private int codigoIdCiudad;
private SimpleStringProperty nombreCiudad;
// creamos la relacion de muchos a uno conla tabla Paises
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "codigoIdPais",nullable = true)
private GS_TablaPaises paises;
// establecemos la relacion de uno a muchos con la tablaComunidades
#OneToMany(targetEntity = GS_TablaComunidades.class, mappedBy =
"ciudades", cascade = CascadeType.ALL)
private List<GS_TablaComunidades> listaComunidades = new
ArrayList<GS_TablaComunidades>();
private static final long serialVersionUID = 1L;
// constructor vacio
public GS_TablaCiudades() {
super();
}
// constructor con parametros
#SuppressWarnings("exports")
public GS_TablaCiudades(int codigoIdCiudad, SimpleStringProperty
nombreCiudad, GS_TablaPaises paises,
List<GS_TablaComunidades> listaComunidades) {
super();
this.codigoIdCiudad = codigoIdCiudad;
this.nombreCiudad = nombreCiudad;
this.paises = paises;
this.listaComunidades = listaComunidades;
}
}
#Entity
#Access(AccessType.PROPERTY)
public class GS_TablaComunidades implements Serializable {
# GeneratedValue ( strategy = GenerationType.TABLE , generator =
"codigoIdComunidad" )
# SequenceGenerator ( name = "codigoIdComunidad" , initialValue = 1 ,
allocationSize = 1 )
#Id
private int codigoIdComunidad;
private SimpleStringProperty nombreComunidad;
// creamos la relacion de muchos a uno con la tabla ciudades
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "codigoIdCiudad",nullable = true)
private GS_TablaCiudades ciudades;
// establecemos la relacion de uno a muchos con la tablaLocalidades
#OneToMany(targetEntity = GS_TablaLocalidades.class, mappedBy =
"comunidades", cascade = CascadeType.ALL)
private List<GS_TablaLocalidades> listaLocalidades = new
ArrayList<GS_TablaLocalidades>();
private static final long serialVersionUID = 1L;
// constructoer vacio
public GS_TablaComunidades() {
super();
}
// constructor con parametros
public GS_TablaComunidades(int codigoIdComunidad, SimpleStringProperty
nombreComunidad, GS_TablaCiudades ciudades,
List<GS_TablaLocalidades> listaLocalidades) {
this.codigoIdComunidad = codigoIdComunidad;
this.nombreComunidad = nombreComunidad;
this.ciudades = ciudades;
this.listaLocalidades = listaLocalidades;
}
}
controller program
package pruebas;
import java.util.List;
import com.jfoenix.controls.*;
import com.jfoenix.controls.cells.editors.TextFieldEditorBuilder;
import com.jfoenix.controls.cells.editors.base.GenericEditableTreeTableCell;
import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject;
import javax.persistence.TypedQuery;
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.control.cell.CheckBoxTreeTableCell;
import javafx.scene.control.cell.ComboBoxTreeTableCell;
import javafx.scene.control.cell.TreeItemPropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import personalModelo.entidades.GS_TablaCiudades;
import personalModelo.entidades.GS_TablaPaises;
import personalModelo.repositorios.GS_RepositorioTablaPaises;
import pruebas.TreeTableViewEditDemo.Gender;
public class PruebaPaisesTreeTableView extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
// Create column FullName (Data type of String).
JFXTreeTableColumn<GS_TablaPaises, String> paisCol = new
JFXTreeTableColumn<GS_TablaPaises, String>("Pais");
// Create 3 sub column for FullName.
JFXTreeTableColumn<GS_TablaPaises, Integer> idPaisCol = new
JFXTreeTableColumn<GS_TablaPaises, Integer>("ID");
JFXTreeTableColumn<GS_TablaPaises, String> nombrePaisCol = new
JFXTreeTableColumn<GS_TablaPaises, String>("Nombre");
JFXTreeTableColumn<GS_TablaPaises, String> capitalPaisCol = new
JFXTreeTableColumn<GS_TablaPaises, String>("Capital");
JFXTreeTableColumn<GS_TablaPaises, String> dominioInternetPaisCol =
new JFXTreeTableColumn<GS_TablaPaises, String>("D.I.");
JFXTreeTableColumn<GS_TablaPaises, List> ciudadCodigoCol = new
JFXTreeTableColumn<GS_TablaPaises, List>("ID");
JFXTreeTableColumn<GS_TablaPaises, List> ciudadNombreCol = new
JFXTreeTableColumn<GS_TablaPaises, List>("Nombre");
JFXTreeTableColumn<GS_TablaPaises, List> ciudadColumna = new
JFXTreeTableColumn<GS_TablaPaises, List>("CIUDADES");
// Single? Column
JFXTreeTableColumn<GS_TablaPaises, Boolean> filtrarPaisCol = new
JFXTreeTableColumn<GS_TablaPaises, Boolean>("Filtro");
// Add sub columns to the pais
paisCol.getColumns().addAll(idPaisCol, nombrePaisCol, capitalPaisCol,
dominioInternetPaisCol, filtrarPaisCol, ciudadNombreCol );
ciudadColumna.getColumns().addAll(ciudadCodigoCol, ciudadNombreCol);
// Se crea la lista con los paise de la tabla o clase entidad
crearListaDePaises();
// Root Item
TreeItem<GS_TablaPaises> itemRoot = new RecursiveTreeItem<>
(observableListaPaises, RecursiveTreeObject::getChildren);
treeTableViewPaises = new JFXTreeTableView<>(itemRoot);
treeTableViewPaises.setEditable(true);
// Add columns to TreeTable.
treeTableViewPaises.getColumns().addAll(paisCol, ciudadColumna);
//treeTableViewPaises.setRoot(itemRoot);
// ponemos la tabla paises a la escucha
tablaPaisALaEscucha();
// ==== SINGLE? (CHECH BOX) ===
filtrarPaisCol.setCellValueFactory(new
Callback<TreeTableColumn.CellDataFeatures<GS_TablaPaises,
Boolean>, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean>
call(TreeTableColumn.CellDataFeatures<GS_TablaPaises,
Boolean> param) {
TreeItem<GS_TablaPaises> treeItemPais = param.getValue();
GS_TablaPaises paisValor = treeItemPais.getValue();
SimpleBooleanProperty booleanProp = new
SimpleBooleanProperty(paisValor.
getFiltrarPais());
booleanProp.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<?
extends Boolean> observable,
Boolean oldValue, Boolean newValue) {
paisValor.setFiltrarPais(newValue);
}
});
return booleanProp;
}
});
filtrarPaisCol.setCellFactory(new Callback<TreeTableColumn<
GS_TablaPaises,Boolean>,TreeTableCell<GS_TablaPaises,Boolean>>() {
#Override
public TreeTableCell<GS_TablaPaises,Boolean> call(
TreeTableColumn<GS_TablaPaises,Boolean> p ) {
CheckBoxTreeTableCell<GS_TablaPaises,Boolean> cell = new
CheckBoxTreeTableCell<GS_TablaPaises,Boolean>();
cell.setAlignment(Pos.CENTER);
return cell;
}
});
// Defines how to fill data for each cell.
// Get value from property of Employee.
idPaisCol.setCellValueFactory(new TreeItemPropertyValueFactory<
GS_TablaPaises, Integer>("codigoIdPais"));
nombrePaisCol.setCellValueFactory(new TreeItemPropertyValueFactory<
GS_TablaPaises, String>("nombrePais"));
capitalPaisCol.setCellValueFactory(new TreeItemPropertyValueFactory<
GS_TablaPaises, String>("capitalPais"));
dominioInternetPaisCol.setCellValueFactory(new
TreeItemPropertyValueFactory<GS_TablaPaises, String>
("dominioInternetPais"));
filtrarPaisCol.setCellValueFactory(new TreeItemPropertyValueFactory<
GS_TablaPaises, Boolean>("filtrarPais"));
StackPane root = new StackPane();
root.setPadding(new Insets(5));
root.getChildren().addAll(treeTableViewPaises);
stage.setTitle("TreeTableView (o7planning.org)");
Scene scene = new Scene(root, 450, 300);
stage.setScene(scene);
//stage.show();
}
// metodo para cargar los datos de l tabla paises
public void crearListaDePaises() {
GS_RepositorioTablaPaises miRepositorio = new
GS_RepositorioTablaPaises();
String query1 = "SELECT tablaP FROM GS_TablaPaises tablaP ";
miRepositorio.miConexion.dameConexion().getTransaction().begin();
TypedQuery<GS_TablaPaises> consultaElementos = miRepositorio.
miConexion.dameConexion().createQuery(query1,GS_TablaPaises.class);
listaPaises = consultaElementos.getResultList();
System.out.println("listaPaises: "+listaPaises.size());
observableListaPaises = FXCollections.observableArrayList(
listaPaises);
miRepositorio.miConexion.dameConexion().getTransaction().commit();
miRepositorio.miConexion.cerrarConexion();
}
public void tablaPaisALaEscucha() throws Exception {
treeTableViewPaises.getSelectionModel().selectedItemProperty().
addListener((valor, valorNuevo, valorViejo) -> {
System.out.println(" fila : "+treeTableViewPaises.
getSelectionModel().getSelectedIndex());
});
}
// variable a nivel de clase
private JFXTreeTableView<GS_TablaPaises> treeTableViewPaises;
private List<GS_TablaPaises> listaPaises;
private ObservableList<GS_TablaPaises> observableListaPaises;
private CheckBoxTreeItem<Boolean> checkBoxLista;
}

Related

How to List with objects, split into List.s of different Java objects)

I have a CsvToGame class, this is a model for parsing a CSV file.
import com.opencsv.bean.CsvBindByPosition;
import java.util.Objects;
public class CsvToGame {
#CsvBindByPosition(position = 0)
private String rank;
#CsvBindByPosition(position = 1)
private String name;
#CsvBindByPosition(position = 2)
private String platform;
#CsvBindByPosition(position = 3)
private String year;
#CsvBindByPosition(position = 4)
private String Genre;
#CsvBindByPosition(position = 5)
private String publisher;
#CsvBindByPosition(position = 6)
private String NASales;
#CsvBindByPosition(position = 7)
private String EUSales;
#CsvBindByPosition(position = 8)
private String JPSales;
#CsvBindByPosition(position = 9)
private String otherSales;
#CsvBindByPosition(position = 10)
private String globalSales;
//set and get
//equals and hashcode
There is a parser.
import com.opencsv.bean.CsvToBeanBuilder;
import alex.gusev.Parser.model.CsvToGame;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ParserCsv {
public static ArrayList<CsvToGame> parser(String path) {
try (FileReader fileReader = new FileReader(path)) {
ArrayList<CsvToGame> all = new ArrayList<>();
List<CsvToGame> beans = new CsvToBeanBuilder(fileReader)
.withType(CsvToGame.class)
.build()
.parse();
all.addAll(beans);
return all;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
**I need a parsed Csv file, I need to upload it to the database.
According to the database structure.**
enter image description here
**
How to implement it?
Sample code please!**
I created a set of classes, according to the structure of the database, but I can not help but connect it all.
enter image description here

Performance problem when query a many-to-one relation by jpa

I use spring-boot-data-jpa-2.0 to get data from db. A table has many-to-one relation, and the query speed is too slow, 1000 lines data with foreign key will cost 15s, but by native sql it will cost only 0.07s. I search the issue and found that it is because 1+n problem.
Some solution that says use 'join fetch' in hql can solve. When I use the 'join fetch' in hql, query speed not change.
The system designed as a pure rest service, with spring boot framework.
contract entity
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "MA_CONTRACTINFO_B")
public class MaContractinfoB implements java.io.Serializable {
// Fields
private String contractcd;
private MaDepartmentB maDepartmentB;
private Double contractid;
private String contractnm;
private String partya;
private String deputycontract;
private String prjtype;
private Double fundt;
private String bustype;
private String contractstatus;
private Double contractyear;
private String fundratio;
private LocalDateTime signdate;
private String prj;
private LocalDateTime loaddate;
private String udep;
private Double fundaccont;
private Double receipt;
private Double fundacctot;
private Double receiptot;
private String loc;
private String riskasscd;
private String rm;
private String pm;
private Double fundaccrec;
private String adminleader;
private String techleader;
private String leader;
private String progress;
private String cashadmin;
private String timetask;
private String contracttp;
// Constructors
/** default constructor */
public MaContractinfoB() {
}
/** minimal constructor */
public MaContractinfoB(String contractcd) {
this.contractcd = contractcd;
}
/** full constructor */
public MaContractinfoB(String contractcd, MaDepartmentB maDepartmentB, Double contractid, String contractnm,
String partya, String deputycontract, String prjtype, Double fundt, String bustype, String contractstatus,
Double contractyear, String fundratio, LocalDateTime signdate, String prj, LocalDateTime loaddate,
String udep, Double fundaccont, Double receipt, Double fundacctot, Double receiptot, String loc,
String riskasscd, String rm, String pm, Double fundaccrec, String adminleader, String techleader,
String leader, String progress, String cashadmin, String timetask, String contracttp) {
this.contractcd = contractcd;
this.maDepartmentB = maDepartmentB;
this.contractid = contractid;
this.contractnm = contractnm;
this.partya = partya;
this.deputycontract = deputycontract;
this.prjtype = prjtype;
this.fundt = fundt;
this.bustype = bustype;
this.contractstatus = contractstatus;
this.contractyear = contractyear;
this.fundratio = fundratio;
this.signdate = signdate;
this.prj = prj;
this.loaddate = loaddate;
this.udep = udep;
this.fundaccont = fundaccont;
this.receipt = receipt;
this.fundacctot = fundacctot;
this.receiptot = receiptot;
this.loc = loc;
this.riskasscd = riskasscd;
this.rm = rm;
this.pm = pm;
this.fundaccrec = fundaccrec;
this.adminleader = adminleader;
this.techleader = techleader;
this.leader = leader;
this.progress = progress;
this.cashadmin = cashadmin;
this.timetask = timetask;
this.contracttp = contracttp;
}
// Property accessors
#Id
#Column(name = "CONTRACTCD", unique = true, nullable = false)
public String getContractcd() {
return this.contractcd;
}
public void setContractcd(String contractcd) {
this.contractcd = contractcd;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "DEPID")
public MaDepartmentB getMaDepartmentB() {
return this.maDepartmentB;
}
public void setMaDepartmentB(MaDepartmentB maDepartmentB) {
this.maDepartmentB = maDepartmentB;
}
#Column(name = "CONTRACTID", precision = 38, scale = 8)
public Double getContractid() {
return this.contractid;
}
public void setContractid(Double contractid) {
this.contractid = contractid;
}
#Column(name = "CONTRACTNM")
public String getContractnm() {
return this.contractnm;
}
public void setContractnm(String contractnm) {
this.contractnm = contractnm;
}
#Column(name = "PARTYA")
public String getPartya() {
return this.partya;
}
public void setPartya(String partya) {
this.partya = partya;
}
#Column(name = "DEPUTYCONTRACT")
public String getDeputycontract() {
return this.deputycontract;
}
public void setDeputycontract(String deputycontract) {
this.deputycontract = deputycontract;
}
#Column(name = "PRJTYPE")
public String getPrjtype() {
return this.prjtype;
}
public void setPrjtype(String prjtype) {
this.prjtype = prjtype;
}
#Column(name = "FUNDT", precision = 38, scale = 8)
public Double getFundt() {
return this.fundt;
}
public void setFundt(Double fundt) {
this.fundt = fundt;
}
#Column(name = "BUSTYPE")
public String getBustype() {
return this.bustype;
}
public void setBustype(String bustype) {
this.bustype = bustype;
}
#Column(name = "CONTRACTSTATUS")
public String getContractstatus() {
return this.contractstatus;
}
public void setContractstatus(String contractstatus) {
this.contractstatus = contractstatus;
}
#Column(name = "CONTRACTYEAR", precision = 38, scale = 8)
public Double getContractyear() {
return this.contractyear;
}
public void setContractyear(Double contractyear) {
this.contractyear = contractyear;
}
#Column(name = "FUNDRATIO")
public String getFundratio() {
return this.fundratio;
}
public void setFundratio(String fundratio) {
this.fundratio = fundratio;
}
#Column(name = "SIGNDATE", length = 11)
public LocalDateTime getSigndate() {
return this.signdate;
}
public void setSigndate(LocalDateTime signdate) {
this.signdate = signdate;
}
#Column(name = "PRJ")
public String getPrj() {
return this.prj;
}
public void setPrj(String prj) {
this.prj = prj;
}
#Column(name = "LOADDATE", length = 11)
public LocalDateTime getLoaddate() {
return this.loaddate;
}
public void setLoaddate(LocalDateTime loaddate) {
this.loaddate = loaddate;
}
#Column(name = "UDEP")
public String getUdep() {
return this.udep;
}
public void setUdep(String udep) {
this.udep = udep;
}
#Column(name = "FUNDACCONT", precision = 38, scale = 8)
public Double getFundaccont() {
return this.fundaccont;
}
public void setFundaccont(Double fundaccont) {
this.fundaccont = fundaccont;
}
#Column(name = "RECEIPT", precision = 38, scale = 8)
public Double getReceipt() {
return this.receipt;
}
public void setReceipt(Double receipt) {
this.receipt = receipt;
}
#Column(name = "FUNDACCTOT", precision = 38, scale = 8)
public Double getFundacctot() {
return this.fundacctot;
}
public void setFundacctot(Double fundacctot) {
this.fundacctot = fundacctot;
}
#Column(name = "RECEIPTOT", precision = 38, scale = 8)
public Double getReceiptot() {
return this.receiptot;
}
public void setReceiptot(Double receiptot) {
this.receiptot = receiptot;
}
#Column(name = "LOC")
public String getLoc() {
return this.loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
#Column(name = "RISKASSCD")
public String getRiskasscd() {
return this.riskasscd;
}
public void setRiskasscd(String riskasscd) {
this.riskasscd = riskasscd;
}
#Column(name = "RM")
public String getRm() {
return this.rm;
}
public void setRm(String rm) {
this.rm = rm;
}
#Column(name = "PM")
public String getPm() {
return this.pm;
}
public void setPm(String pm) {
this.pm = pm;
}
#Column(name = "FUNDACCREC", precision = 38, scale = 8)
public Double getFundaccrec() {
return this.fundaccrec;
}
public void setFundaccrec(Double fundaccrec) {
this.fundaccrec = fundaccrec;
}
#Column(name = "ADMINLEADER")
public String getAdminleader() {
return this.adminleader;
}
public void setAdminleader(String adminleader) {
this.adminleader = adminleader;
}
#Column(name = "TECHLEADER")
public String getTechleader() {
return this.techleader;
}
public void setTechleader(String techleader) {
this.techleader = techleader;
}
#Column(name = "LEADER", length = 20)
public String getLeader() {
return this.leader;
}
public void setLeader(String leader) {
this.leader = leader;
}
#Column(name = "PROGRESS", length = 1000)
public String getProgress() {
return this.progress;
}
public void setProgress(String progress) {
this.progress = progress;
}
#Column(name = "CASHADMIN", length = 20)
public String getCashadmin() {
return this.cashadmin;
}
public void setCashadmin(String cashadmin) {
this.cashadmin = cashadmin;
}
#Column(name = "TIMETASK", length = 2000)
public String getTimetask() {
return this.timetask;
}
public void setTimetask(String timetask) {
this.timetask = timetask;
}
#Column(name = "CONTRACTTP", length = 50)
public String getContracttp() {
return this.contracttp;
}
public void setContracttp(String contracttp) {
this.contracttp = contracttp;
}
/**
* toString
*
* #return String
*/
#Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getClass().getName()).append("#").append(Integer.toHexString(hashCode())).append(" [");
buffer.append("contractcd").append("='").append(getContractcd()).append("' ");
buffer.append("maDepartmentB").append("='").append(getMaDepartmentB()).append("' ");
buffer.append("contractid").append("='").append(getContractid()).append("' ");
buffer.append("contractnm").append("='").append(getContractnm()).append("' ");
buffer.append("partya").append("='").append(getPartya()).append("' ");
buffer.append("deputycontract").append("='").append(getDeputycontract()).append("' ");
buffer.append("prjtype").append("='").append(getPrjtype()).append("' ");
buffer.append("fundt").append("='").append(getFundt()).append("' ");
buffer.append("bustype").append("='").append(getBustype()).append("' ");
buffer.append("contractstatus").append("='").append(getContractstatus()).append("' ");
buffer.append("contractyear").append("='").append(getContractyear()).append("' ");
buffer.append("fundratio").append("='").append(getFundratio()).append("' ");
buffer.append("signdate").append("='").append(getSigndate()).append("' ");
buffer.append("prj").append("='").append(getPrj()).append("' ");
buffer.append("loaddate").append("='").append(getLoaddate()).append("' ");
buffer.append("udep").append("='").append(getUdep()).append("' ");
buffer.append("fundaccont").append("='").append(getFundaccont()).append("' ");
buffer.append("receipt").append("='").append(getReceipt()).append("' ");
buffer.append("fundacctot").append("='").append(getFundacctot()).append("' ");
buffer.append("receiptot").append("='").append(getReceiptot()).append("' ");
buffer.append("loc").append("='").append(getLoc()).append("' ");
buffer.append("riskasscd").append("='").append(getRiskasscd()).append("' ");
buffer.append("rm").append("='").append(getRm()).append("' ");
buffer.append("pm").append("='").append(getPm()).append("' ");
buffer.append("fundaccrec").append("='").append(getFundaccrec()).append("' ");
buffer.append("adminleader").append("='").append(getAdminleader()).append("' ");
buffer.append("techleader").append("='").append(getTechleader()).append("' ");
buffer.append("leader").append("='").append(getLeader()).append("' ");
buffer.append("progress").append("='").append(getProgress()).append("' ");
buffer.append("cashadmin").append("='").append(getCashadmin()).append("' ");
buffer.append("timetask").append("='").append(getTimetask()).append("' ");
buffer.append("contracttp").append("='").append(getContracttp()).append("' ");
buffer.append("]");
return buffer.toString();
}
}
department entity
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "MA_DEPARTMENT_B")
public class MaDepartmentB implements java.io.Serializable {
// Fields
private Long id;
private String name;
private String leader;
private Set<MaContractinfoB> maContractinfoBs = new HashSet<MaContractinfoB>(0);
private Set<MaContraimB> maContraimBs = new HashSet<MaContraimB>(0);
// Constructors
/** default constructor */
public MaDepartmentB() {
}
/** minimal constructor */
public MaDepartmentB(Long id) {
this.id = id;
}
/** full constructor */
public MaDepartmentB(Long id, String name, String leader, Set<MaContractinfoB> maContractinfoBs,
Set<MaContraimB> maContraimBs) {
this.id = id;
this.name = name;
this.leader = leader;
this.maContractinfoBs = maContractinfoBs;
this.maContraimBs = maContraimBs;
}
// Property accessors
#Id
#Column(name = "ID", unique = true, nullable = false, precision = 10, scale = 0)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "NAME")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "LEADER")
public String getLeader() {
return this.leader;
}
public void setLeader(String leader) {
this.leader = leader;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "maDepartmentB")
public Set<MaContractinfoB> getMaContractinfoBs() {
return this.maContractinfoBs;
}
public void setMaContractinfoBs(Set<MaContractinfoB> maContractinfoBs) {
this.maContractinfoBs = maContractinfoBs;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "maDepartmentB")
public Set<MaContraimB> getMaContraimBs() {
return this.maContraimBs;
}
public void setMaContraimBs(Set<MaContraimB> maContraimBs) {
this.maContraimBs = maContraimBs;
}
/**
* toString
*
* #return String
*/
#Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getClass().getName()).append("#").append(Integer.toHexString(hashCode())).append(" [");
buffer.append("id").append("='").append(getId()).append("' ");
buffer.append("name").append("='").append(getName()).append("' ");
buffer.append("leader").append("='").append(getLeader()).append("' ");
buffer.append("maContractinfoBs").append("='").append(getMaContractinfoBs()).append("' ");
buffer.append("maContraimBs").append("='").append(getMaContraimBs()).append("' ");
buffer.append("]");
return buffer.toString();
}
}
jparepository
public interface MaContractinfoBRepository extends JpaRepository<MaContractinfoB, Long> {
#Query("from MaContractinfoB c join fetch c.maDepartmentB")
List<MaContractinfoB> findAll();
#Query("select contractnm from MaContractinfoB")
List<String> findAllName();
// #Query("from MaContractinfoB c join fetch c.maDepartmentB")
// List test();
}
In MaContractinfoBRepository, When I use findAllName function, it will immediately return 1000 contract names in 0.05s. When I use findAll, it will cost 15s to get 1000 data with department entity, even I add join fetch. But if I get it by native sql in db tool such as navicat, it will cost only 0.07s.
Is any keypoint I missed? How to query the MaContractinfoB table not so slowly?
This is happening because internally with 'fetch' command also hibernate is lazy loading all the rows of Department entity for each Contract id whenever you call the findAll() method. So if there are n rows in Department for 1 Contract and in total there are m Contracts then the total number of calls to the database would be 'm * n'.
One way around this is by using DTO projections. Data Transfer Objects is an easy way to define all the required columns in one query and hit the database for once.
I have found this article useful which shows multiple ways of writing DTO projections.
https://thoughts-on-java.org/dto-projections/
One of the mentioned way is: Using JPQL you can use a constructor expression to define a constructor call with the keyword new followed by the fully classified class name of your DTO and a list of constructor parameters in curly braces.
Something like this:
TypedQuery<ContractWithDepartmentDetails> q = em.createQuery(
"SELECT new com.practice.model.ContractWithDepartmentDetails(c.id, c.name, d.name) FROM contract c JOIN c.department d",
ContractWithDepartmentDetails.class);

Error using Spel expressions in Spring JPA native query( converting string to Hexa)

I created a repository with the following method.
#Modifying(clearAutomatically = true)
#Query(
value = "UPDATE address SET address_line_1 = :#{#address.getAddressLine1()} , address_line_2 = :#{#address.getAddressLine2()} ," +
" address_line_3 = :#{#address.getAddressLine3()} , city = :#{#address.getCity()} , address_type = :#{#address.getAddressType().toString()} ," +
" postal_code = :#{#address.getPostalCode()} , state = :#{#address.getState().toString()} , country= :#{#address.getCountry().toString()} , residence_type = :#{#address.getResidenceType().toString()} ," +
" discriminator = :#{#address.getAddressType().toString()},created_by = :#{#address.getCreatedBy()} , created_date = :#{#address.getCreatedDateTime()} WHERE address_id = :#{#address.getId()}",
nativeQuery = true)
void updateAddress(#Param("address") Address address);
During the updates the addressLine2/ addressLine3 is converted to and stored in the database in hexa format.
For example, if addressLine2 is passed into the method as 1OFFICE OF HOBBITS, it is converted to and stored as \x314f6666696365206f6620486f6262697473
This only occurs on a few updates (not all). I cannot discern a distinguishable pattern among the values that are updated as expected and those that are converted to hexa format.
HELP!!
Additional Info:
I even tried without the Spel Expression and I see the same error:
Here are some more details:
Repository Interface:
import com.company.domain.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface AddressRepository extends JpaRepository<Address, Long> {
#Modifying(clearAutomatically = true)
#Query(
value = "UPDATE address SET address_line_1 = :address_line_1 , address_line_2 = :address_line_2 ," +
" address_line_3 = :address_line_3 WHERE address_id = :address_id ",
nativeQuery = true)
void updateAddress(#Param("address_line_1") String address_line_1,#Param("address_line_2") String address_line_2,#Param("address_line_3") String address_line_3,#Param("address_id") Long address_id);
}
Service Class:
import com.company.hibernate.AddressRepository;
import com.company.domain.Address;
import com.company.domain.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Class by AddressServiceImpl
*/
#Service
public class AddressServiceImpl implements AddressService {
#Autowired
private AddressRepository addressRepository;
#Override
public void updateAddress(Address address) {
System.out.println(address);
System.out.println(address.getId());
System.out.println(address.getAddressLine2());
addressRepository.updateAddress(address.getAddressLine1() , address.getAddressLine2() ,
address.getAddressLine3(),address.getId());
}
}
When I call the service method
addressService.updateAddress(address);
I see the following sysouts:
{"addressId":2000112115,"addressLine1":"2001 Hussle
Road2","addressLine2":"Office of Hobbits","addressLine3":null }
2000112115
Office of Hobbits
But In the database I see : the following for address_line_2
\x4f6666696365206f6620486f6262697473
Updated 2 - Added address class:
package com.company.domain;
import com.company.common.Identifiable;
import com.company.enums.AddressType;
import com.company.ResidenceType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.EqualsExclude;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.HashCodeExclude;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.time.LocalDateTime;
public class Address implements Identifiable<Long>, Serializable {
private static final long serialVersionUID = 599052439022921076L;
protected static final String INVALID_ADDRESS = "InvalidAddress";
private Long addressId;
private String addressLine1;
private String addressLine2;
private String addressLine3;
#Override
public Long getId() {
return addressId;
}
public void setId(Long id) {
this.addressId = id;
}
public Customer getCustomer() {
return customer;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getAddressLine3() {
return addressLine3;
}
public void setAddressLine3(String addressLine3) {
this.addressLine3 = addressLine3;
}
#Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj, false);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, false);
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}

TreeTableView data model

I am new to Java 8 world(with lambdas, functions etc,) and building a JavaFX 8 application, i am struggling to build the data model(TreeItem) for TreeTableView. The data is fetched from database as ObservableList<Certificate>. A Certificate object with ca=true could have children which could be tracked by issuerName field. My aim is to build a TreeTableView with various columns, where Certificates are presented as
Root(a dummy node)
|
|--Certificate1 (could be ca=false with no issuer match to any ca OR ca=true with no child)
|--Certificate2
|--Certificate3 (ca=true)
|--Certifciate4 (issuer name machted with Certificate3)
|--Certificate5 (issuer name machted with Certificate3)
|--Certificate6
|--Certificate7 (ca=true)
|--Certifciate8 (issuer name machted with Certificate7)
|--Certificate9 (issuer name machted with Certificate7)
Class Certificate looks like
public class Certificate implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private boolean ca;
private String issuerName;
...
In next step want some add/remove/edit functionality on this view.
Can anyone guide me how can i achieve this???
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeTableView;
import javafx.stage.Stage;
public class TreeTableSampleApp extends Application {
#Override public void start(Stage primaryStage) {
primaryStage.setTitle("TreeTable View Sample");
primaryStage.setScene(new Scene(new TreeTableSample()));
primaryStage.sizeToScene();
primaryStage.show();
TreeTableView<?> treeTableView = (TreeTableView<?>) primaryStage.getScene().getRoot().lookup(".tree-table-view");
treeTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
public static void main(String[] args) {
Application.launch(args);
}
}
import java.util.Arrays;
import java.util.List;
import ensemble.Sample;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.layout.Pane;
public class TreeTableSample extends Pane {
List<Employee> employees = Arrays.<Employee> asList(new Employee("Ethan Williams", "ethan.williams#example.com"),
new Employee("Emma Jones", "emma.jones#example.com"), new Employee("Michael Brown", "michael.brown#example.com"),
new Employee("Anna Black", "anna.black#example.com"), new Employee("Rodger York", "roger.york#example.com"),
new Employee("Susan Collins", "susan.collins#example.com"));
final TreeItem<Employee> root = new TreeItem<>(new Employee("Sales Department", ""));
public TreeTableSample() {
root.setExpanded(true);
employees.stream().forEach((employee) -> {
root.getChildren().add(new TreeItem<>(employee));
});
TreeTableColumn<Employee, String> empColumn = new TreeTableColumn<>("Employee");
empColumn.setPrefWidth(150);
empColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> new ReadOnlyStringWrapper(
param.getValue().getValue().getName()));
TreeTableColumn<Employee, String> emailColumn = new TreeTableColumn<>("Email");
emailColumn.setPrefWidth(190);
emailColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> new ReadOnlyStringWrapper(
param.getValue().getValue().getEmail()));
TreeTableView<Employee> treeTableView = new TreeTableView<>(root);
treeTableView.getColumns().setAll(empColumn, emailColumn);
getChildren().add(treeTableView);
}
public class Employee {
private SimpleStringProperty name;
private SimpleStringProperty email;
public SimpleStringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(this, "name");
}
return name;
}
public SimpleStringProperty emailProperty() {
if (email == null) {
email = new SimpleStringProperty(this, "email");
}
return email;
}
private Employee(String name, String email) {
this.name = new SimpleStringProperty(name);
this.email = new SimpleStringProperty(email);
}
public String getName() {
return name.get();
}
public void setName(String fName) {
name.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
}
}

methods in an ejb session bean for an entity dont work in a spring MVC project

I created a maven entreprise application project, in the ejb module i put my entities in a package and i generated my session beans in an other package and i deployed my ejb module in glassfish,in the web module i added dependencies of spring and I created a controller that search the session bean and call the methode find all() but it doesnt get my objects stored in database, what should i do?
Category entity
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author DELL
*/
#Entity
#Table(name = "categorie")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Categorie.findAll", query = "SELECT c FROM Categorie c"),
#NamedQuery(name = "Categorie.findByIdCategorie", query = "SELECT c FROM Categorie c WHERE c.idCategorie = :idCategorie"),
#NamedQuery(name = "Categorie.findByDescription", query = "SELECT c FROM Categorie c WHERE c.description = :description"),
#NamedQuery(name = "Categorie.findByName", query = "SELECT c FROM Categorie c WHERE c.name = :name"),
#NamedQuery(name = "Categorie.findByNomPhoto", query = "SELECT c FROM Categorie c WHERE c.nomPhoto = :nomPhoto")})
public class Categorie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idCategorie")
private Integer idCategorie;
#Size(max = 255)
#Column(name = "description")
private String description;
#Size(max = 20)
#Column(name = "name")
private String name;
#Size(max = 255)
#Column(name = "nomPhoto")
private String nomPhoto;
#Lob
#Column(name = "photo")
private byte[] photo;
#OneToMany(mappedBy = "idCategorie")
private List<Produit> produitList;
public Categorie() {
}
public Categorie(Integer idCategorie) {
this.idCategorie = idCategorie;
}
public Integer getIdCategorie() {
return idCategorie;
}
public void setIdCategorie(Integer idCategorie) {
this.idCategorie = idCategorie;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNomPhoto() {
return nomPhoto;
}
public void setNomPhoto(String nomPhoto) {
this.nomPhoto = nomPhoto;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
#XmlTransient
public List<Produit> getProduitList() {
return produitList;
}
public void setProduitList(List<Produit> produitList) {
this.produitList = produitList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idCategorie != null ? idCategorie.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Categorie)) {
return false;
}
Categorie other = (Categorie) object;
if ((this.idCategorie == null && other.idCategorie != null) || (this.idCategorie != null && !this.idCategorie.equals(other.idCategorie))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.entities.Categorie[ idCategorie=" + idCategorie + " ]";
}
}
AbstractFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* #author DELL
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
CategorieFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import com.mycompany.entities.Categorie;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author DELL
*/
#Stateless
public class CategorieFacade extends AbstractFacade<Categorie> implements CategorieFacadeLocal {
#PersistenceContext(unitName = "com.mycompany_ProjetCommerce-ejb_ejb_1.0-SNAPSHOTPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategorieFacade() {
super(Categorie.class);
}
}
CategorieFacadeLocal
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import com.mycompany.entities.Categorie;
import java.util.List;
import javax.ejb.Local;
/**
*
* #author DELL
*/
#Local
public interface CategorieFacadeLocal {
void create(Categorie categorie);
void edit(Categorie categorie);
void remove(Categorie categorie);
Categorie find(Object id);
List<Categorie> findAll();
List<Categorie> findRange(int[] range);
int count();
}
CategorieController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.controlleur;
import com.mycompany.dao.CategorieFacadeLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("categorie")
public class CategorieController {
CategorieFacadeLocal categorieFacade = lookupCategorieFacadeLocal();
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap modelmap){
modelmap.put("listeCategorie", categorieFacade.findAll());
return "index";
}
private CategorieFacadeLocal lookupCategorieFacadeLocal() {
try {
Context c = new InitialContext();
return (CategorieFacadeLocal) c.lookup("java:global/com.mycompany_ProjetCommerce-ear_ear_1.0-SNAPSHOT/com.mycompany_ProjetCommerce-ejb_ejb_1.0-SNAPSHOT/CategorieFacade!com.mycompany.dao.CategorieFacadeLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}

Resources