JTable TableModel problem in Java - java

I can show my data in a JTable without a problem, but when I want to filter while my app is running, the JTable is not showing me data changes. I searched for it and found a class named TableModel but I can't write my AbstractTableModel. Can anyone show me how I can do this?
Personelz.Java
package deneme.persistence;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* #author İbrahim AKGÜN
*/
#Entity
#Table(name = "PERSONELZ", catalog = "tksDB", schema = "dbo")
#NamedQueries({#NamedQuery(name = "Personelz.findAll", query = "SELECT p FROM Personelz p"), #NamedQuery(name = "Personelz.findByPersonelıd", query = "SELECT p FROM Personelz p WHERE p.personelıd = :personelıd"), #NamedQuery(name = "Personelz.findByAd", query = "SELECT p FROM Personelz p WHERE p.ad = :ad"), #NamedQuery(name = "Personelz.findBySoyad", query = "SELECT p FROM Personelz p WHERE p.soyad = :soyad")})
public class Personelz implements Serializable {
#Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "PERSONELID", nullable = false )
private Integer personelıd;
#Column(name = "AD", length = 50)
private String ad;
#Column(name = "SOYAD", length = 50)
private String soyad;
#Column(name = "YAS")
private Integer yas;
public Personelz() {
}
public Personelz(Integer personelıd) {
this.personelıd = personelıd;
}
public Integer getPersonelıd() {
return personelıd;
}
public void setPersonelıd(Integer personelıd) {
this.personelıd = personelıd;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
String oldAd = this.ad;
this.ad = ad;
changeSupport.firePropertyChange("ad", oldAd, ad);
}
public String getSoyad() {
return soyad;
}
public void setSoyad(String soyad) {
String oldSoyad = this.soyad;
this.soyad = soyad;
changeSupport.firePropertyChange("soyad", oldSoyad, soyad);
}
public Integer getYas() {
return yas;
}
public void setYas(Integer yas){
this.yas = yas;
}
TABLEMODEL
public class TableModel extends AbstractTableModel {
String[] headers;
List<Personelz> personel;
int row;
int column;
Object[][] per;
/** Creates a new instance of TableModel */
#SuppressWarnings("empty-statement")
public TableModel(List<Personelz> p) {
this.personel = p;
column=2;
row=this.personel.size();
headers=new String[column];
headers[0]="AD";
headers[1]="SOYAD";
per={p.toArray(),p.toArray()};
}
public int getColumnCount()
{
return column;
}
public int getRowCount()
{
return row;
}
public Object getValueAt(int rowIndex, int kolonindex)
{
return per[rowIndex][kolonindex];
}
public String getColumnName(int i)
{
return headers[i];
}

I suggest reading this How to Use Tables (from the Java Tutorials Using Swing Components)
Basically the TableModel has to notify the Table of changed data by firing the appropriate Events. See here

There is a very good library called GlazedLists that makes it a lot simpler to work with lists and tables, including column sorting and row filtering.
Its definitely worth taking a look.
http://publicobject.com/glazedlists/
HTH

You should utilize the TableModelListener interface, which your JTable implements. Once you add your table to your TableModel, call the appropriate fireTableChanged()-type event that AbstractTableModel implements. This should force your JTable to update.
You will still need to implement a method to reset your data in your model when your filter operation returns. it should be in this method that you call your fireTableChanged() event. you also should ensure that you are in the AWT thread when you fire the table changed event.

Related

Vaadin Grid. Problem with setting column based on entity property

I'm using spring and MySQL as database to ORM. Im trying to display entity properties in grid in one of my Views. Item Id is passed by Url, and Items are set after constructor. In this scenario I'm trying to display audits that given enterprise had in the past. When navigating to given view, exception is beeing thrown:
There was an exception while trying to navigate to 'EnterpriseView/151' with the root cause 'java.lang.IllegalArgumentException: Multiple columns for the same property: auditId
What does it mean, as when I'm checking columns in database there in only one auditId in audit Table?
There are my classes:
import com.sun.istack.NotNull;
import javax.persistence.*;
#Entity
#Table
public class Audit {
private int auditId;
private Trip trip;
private User user;
private Enterprise enterprise;
public Audit() {
}
public Audit(Enterprise enterprise) {
this.enterprise = enterprise;
}
#Id
#GeneratedValue
#NotNull
#Column(unique = true)
public int getAuditId() {
return auditId;
}
#ManyToOne
#JoinColumn(name = "TRIPS_ID")
public Trip getTrip() {
return trip;
}
#ManyToOne
#JoinColumn(name = "USER_ID")
public User getUser() {
return user;
}
#ManyToOne
#JoinColumn(name = "ENTERPRISE_ID")
public Enterprise getEnterprise() {
return enterprise;
}
public void setAuditId(int auditId) {
this.auditId = auditId;
}
public void setTrip(Trip trip) {
this.trip = trip;
}
public void setUser(User user) {
this.user = user;
}
public void setEnterprise(Enterprise enterprise) {
this.enterprise = enterprise;
}
}
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.*;
import com.wtd.assistant.frontend.dao.AuditDao;
import com.wtd.assistant.frontend.dao.EnterpriseDao;
import com.wtd.assistant.frontend.domain.Audit;
import com.wtd.assistant.frontend.domain.Enterprise;
import java.util.List;
import java.util.Optional;
#Route("EnterpriseView")
public class EnterpriseView extends VerticalLayout implements HasUrlParameter<String>, AfterNavigationObserver{
private EnterpriseDao enterpriseDao;
private AuditDao auditDao;
private Grid<Audit> grid;
private List<Audit> auditsList;
private Optional<Enterprise> enterprise;
private String enterpriseId;
public EnterpriseView(EnterpriseDao enterpriseDao, AuditDao auditDao) {
this.enterpriseDao = enterpriseDao;
this.auditDao = auditDao;
this.grid = new Grid<>(Audit.class);
VerticalLayout layout = new VerticalLayout();
layout.add(grid);
grid.addColumns( "auditId" );
}
#Override
public void setParameter(BeforeEvent event, String parameter) {
enterpriseId = parameter;
System.out.println("setParameter(), enterpriseId: " + enterpriseId);
}
#Override
public void afterNavigation(AfterNavigationEvent event) {
enterprise = enterpriseDao.findById(Integer.valueOf(enterpriseId));
System.out.println("EnterpriseId: " + enterprise.get().getEnterpriseId());
auditsList = enterprise.get().getAudits();
grid.setItems(auditsList);
}
}
I tried renaming auditId property but obviously that didn't bring any result
Kind regards
Kiemoon
In the constructor of the EnterpriseView you have this code:
grid.addColumns( "auditId" );
Thats where your duplicate is comming from

composite key join columns

My table VENDORBRANCH has composite keys: "vendorCode" and "vendorBranchCode" which I have defined using the #Id annotation and using #IdClass. The field "vendorCode" is referenced as a foreign key in VENDORCRTERMS class. I'm using postgresql db.
Right now my sql query in the service implimentation looks like this but i want to include composite keys in the query:
Query<?> query = session.createQuery("from VENDORBRANCH where vendorCode = ?");
query.setParameter(0, mf01_vendorCode);
I'm very new to hibernate so tried a few options for the select query but I'm not sure if it's correct to do it this way. So, what would be the best select statement to use for a composite key??
VENDORBRANCH class:
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.parkson.poMain.backend.data.VENDORBRANCH.VBpk;
#SuppressWarnings("serial")
#Entity
#IdClass(VBpk.class)
public class VENDORBRANCH implements Serializable {
#Id
private String vendorCode;
#Id
private String vendorBranchCode;
//getters and setters
// inner class defined for primary key(composite keys)
public static class VBpk implements Serializable {
protected String vendorCode;
protected String vendorBranchCode;
public String getvendorCode() {
return vendorCode;
}
public void vendorCode(String vendorCode) {
this.vendorCode = vendorCode;
}
public String vendorBranchCode() {
return vendorBranchCode;
}
public void vendorBranchCode(String vendorBranchCode) {
this.vendorBranchCode = vendorBranchCode;
}
public VBpk(){}
public VBpk(String vendorCode,String vendorBranchCode){
this.vendorCode = vendorCode;
this.vendorBranchCode = vendorBranchCode;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((vendorBranchCode == null) ? 0 : vendorBranchCode.hashCode());
result = prime * result + ((vendorCode == null) ? 0 : vendorCode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VBpk other = (VBpk) obj;
if (vendorBranchCode == null) {
if (other.vendorBranchCode != null)
return false;
} else if (!vendorBranchCode.equals(other.vendorBranchCode))
return false;
if (vendorCode == null) {
if (other.vendorCode != null)
return false;
} else if (!vendorCode.equals(other.vendorCode))
return false;
return true;
}
}
}
My other class: VENDORCRTERMS
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#SuppressWarnings("serial")
#Entity
public class VENDORCRTERMS implements Serializable {
#Id
private String vcrId ;
//This is the foreign key referenced from **VENDORBRANCH class**
#ManyToOne
#JoinColumns( {
#JoinColumn(name="vendorcode", nullable = false),
#JoinColumn(name="vendorBranchCode", nullable = false)} )
private VENDORBRANCH vendorbranch_vendorcode = new VENDORBRANCH();
// foreign key referenced from a different class
#ManyToOne
#JoinColumn(name= "creditterms_credittermscode" , nullable = false)
private CREDITTERMS creditterms_credittermscode = new CREDITTERMS();
//getters and setters
}
VENDORBRANCH has defined a composite primary key but in VENDORCRTERMS you only use on #JoinColumn for the reference. This is how the mapping should look like in your case:
#ManyToOne
#JoinColumns( {
#JoinColumn(name="vendorCode", referencedColumnName="vendorCode"),
#JoinColumn(name="vendorBranchCode", referencedColumnName="vendorBranchCode")
} )
private VENDORBRANCH vendorbranch_vendorcode
The reason is: VENDORCRTERMS class is confused because he observed that there are two #ids in VENDORBRANCH. I have a solution for you. What if you make the vendorCode and vendorBranchCode as unique key as well as keeping only one primary key.
#Id
private String vendorCode;
I think this will satisfy your demand.

Binding from database in swing combobox in java

I want to display distinct year in combo box in ascending order. But the output in combox appears to be repetitive, repetitive in the sense that it shows all the elements of the column of database but i want to show only the distinct data of the column . What am i doing wrong?? I have simply done simple database query before in php. I know it is simply but i am not being to address the query in right order, i guess.
My code is as follows.
/*
* 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 my_ui;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* #author enjal
*/
#Entity
#Table(name = "production", catalog = "data2", schema = "")
#NamedQueries({
#NamedQuery(name = "Production.findAll", query = "SELECT p FROM Production p"),
#NamedQuery(name = "Production.findByProductionId", query = "SELECT p FROM Production p WHERE p.productionId = :productionId"),
#NamedQuery(name = "Production.findByCropId", query = "SELECT p FROM Production p WHERE p.cropId = :cropId"),
#NamedQuery(name = "Production.findByLocationId", query = "SELECT p FROM Production p WHERE p.locationId = :locationId"),
#NamedQuery(name = "Production.findByArea", query = "SELECT p FROM Production p WHERE p.area = :area"),
#NamedQuery(name = "Production.findByProductionAmount", query = "SELECT p FROM Production p WHERE p.productionAmount = :productionAmount"),
#NamedQuery(name = "Production.findByYieldAmount", query = "SELECT p FROM Production p WHERE p.yieldAmount = :yieldAmount"),
#NamedQuery(name = "Production.findByYearOfProduction", query = "SELECT DISTINCT p FROM Production p WHERE p.yearOfProduction = :yearOfProduction ORDER BY p.yearOfProduction ASC" )})
//SELECT DISTINCT year_of_production FROM `production` ORDER BY year_of_production ASC
public class Production implements Serializable {
#Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "production_id")
private Integer productionId;
#Basic(optional = false)
#Column(name = "crop_id")
private int cropId;
#Basic(optional = false)
#Column(name = "location_id")
private String locationId;
#Basic(optional = false)
#Column(name = "area")
private double area;
#Basic(optional = false)
#Column(name = "production_amount")
private String productionAmount;
#Basic(optional = false)
#Column(name = "yield_amount")
private double yieldAmount;
#Basic(optional = false)
#Column(name = "year_of_production")
private String yearOfProduction;
public Production() {
}
public Production(Integer productionId) {
this.productionId = productionId;
}
public Production(Integer productionId, int cropId, String locationId, double area, String productionAmount, double yieldAmount, String yearOfProduction) {
this.productionId = productionId;
this.cropId = cropId;
this.locationId = locationId;
this.area = area;
this.productionAmount = productionAmount;
this.yieldAmount = yieldAmount;
this.yearOfProduction = yearOfProduction;
}
public Integer getProductionId() {
return productionId;
}
public void setProductionId(Integer productionId) {
Integer oldProductionId = this.productionId;
this.productionId = productionId;
changeSupport.firePropertyChange("productionId", oldProductionId, productionId);
}
public int getCropId() {
return cropId;
}
public void setCropId(int cropId) {
int oldCropId = this.cropId;
this.cropId = cropId;
changeSupport.firePropertyChange("cropId", oldCropId, cropId);
}
public String getLocationId() {
return locationId;
}
public void setLocationId(String locationId) {
String oldLocationId = this.locationId;
this.locationId = locationId;
changeSupport.firePropertyChange("locationId", oldLocationId, locationId);
}
public double getArea() {
return area;
}
public void setArea(double area) {
double oldArea = this.area;
this.area = area;
changeSupport.firePropertyChange("area", oldArea, area);
}
public String getProductionAmount() {
return productionAmount;
}
public void setProductionAmount(String productionAmount) {
String oldProductionAmount = this.productionAmount;
this.productionAmount = productionAmount;
changeSupport.firePropertyChange("productionAmount", oldProductionAmount, productionAmount);
}
public double getYieldAmount() {
return yieldAmount;
}
public void setYieldAmount(double yieldAmount) {
double oldYieldAmount = this.yieldAmount;
this.yieldAmount = yieldAmount;
changeSupport.firePropertyChange("yieldAmount", oldYieldAmount, yieldAmount);
}
public String getYearOfProduction() {
return yearOfProduction;
}
public void setYearOfProduction(String yearOfProduction) {
String oldYearOfProduction = this.yearOfProduction;
this.yearOfProduction = yearOfProduction;
changeSupport.firePropertyChange("yearOfProduction", oldYearOfProduction, yearOfProduction);
}
#Override
public int hashCode() {
int hash = 0;
hash += (productionId != null ? productionId.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 Production)) {
return false;
}
Production other = (Production) object;
if ((this.productionId == null && other.productionId != null) || (this.productionId != null && !this.productionId.equals(other.productionId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "my_ui.Production[ productionId=" + yearOfProduction + " ]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
I want to display distinct year in combo box in ascending order. But the output in combobox appears to be repetitive, repetitive in the sense that it shows all the elements of the column of database but i want to show only the distinct data of the column
And you say this is the query you are using to accomplish that
#NamedQuery(name = "Production.findByYearOfProduction",
query = "SELECT DISTINCT p FROM Production p
WHERE p.yearOfProduction = :yearOfProduction
ORDER Bp.yearOfProduction ASC" )})
The problem with this query is that it's used to find a list Production entities by the yearOfProduction. So say you use this query with the year 1990. That means that any Production entity that was produced in 1990 with be part of the result set. So the only year of production you will see is 1990.
What you want is just the distinct values in a single column, where the actual Production entity is not necessarily concerned. So your query should look more like
SELECT DISTINCT p.yearOfProduction
FROM Production p
ORDER BY p.yearOfProduction ASC
The return value should be a list of just the distinct years, and having no connection to the Production entity. You may want to do some refactoring to your code, where calling this query will return a List<String>. And that's the list you want to use for your combo box, not a List<Production>. Where should you do this refactoring? I can't tell, as you haven't provided the code where you call this query.
Note: So what you should do is create a separate #NamedQuery, and the one you currently have, I think you want to keep for maybe a different combo box maybe, where after a year is selected from the first combo box, the second one is populate with all Production entities for that year. Also note your toString just lists the year of production. So if you want some other representation of the Production entity in a the second combo box, you should change that also.
Also keep in mind when you auto-create an entity in Netbeans, It will create a findAll query and a query findByXxx query for each property of the entity. That's it. All the queries are meant to return a list of Production entities using one that property as the parameter for finding matching results. Any other return types you want (in this case a list of strings) or different parameter queries, you need to create a customized query

JPA+Hibernate MySql database schema changes does not reflect

In my spring web service I am accessing a my sql database with JPA+Hibernate. When I changed my database schema in the database, those changes are not reflecting from my web service.
In more detail I have added a new column formcategoryid to applicationforms table and it is added to JPA annotated class as a field. Now when I execute the query
SELECT x.formid,x.formcategoryid,x.formname FROM com.business.objects.ApplicationForms AS x WHERE x.adminroleid LIKE '3'
It gives the exception,
Caused by: org.hibernate.QueryException: could not resolve property: formcategoryid of: com.business.objects.ApplicationForms
Any idea on this?
UPDATE
My ApplicationForms class is like
package com.business.objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "applicationforms")
public class ApplicationForms {
#Id
#GeneratedValue
private int formid;
private int formcategoryid;
private int adminroleid;
private String formname;
.
.
public int getFormid() {
return formid;
}
public void setFormid(int formid) {
this.formid = formid;
}
public int getFormcategoryid() {
return formcategoryid;
}
public void setFormcategoryid(int formcategoryid) {
this.formcategoryid = formcategoryid;
}
public int getAdminroleid() {
return adminroleid;
}
public void setAdminroleid(int adminroleid) {
this.adminroleid = adminroleid;
}
public String getFormname() {
return formname;
}
public void setFormname(String formname) {
this.formname = formname;
}
}

How to draw database Table items onto a TableView using hibernate

Thank you all with the help so far in my project.
I've been looking at this for most of today, but have been unsuccessful in getting any helpful material.
My project is in Java/ JavaFx, Hibernate and H2. So far I can persist items into the database but I cant figure out how to go about pulling the data onto a TableView. I've gone as far as drawing the data onto System.out.println but nothing more.
These are my classes:
This Class creates the database object, NewBeautifulKiwi:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "KIWI_TABLE")
public class NewBeautifulKiwi implements Serializable {
#Id
#GeneratedValue
private int KiwiId;
private String Kiwi;
public int getKiwiId() {
return KiwiId;
}
public void setKiwiId(int KiwiId) {
this.KiwiId = KiwiId;
}
public String getKiwi() {
return Kiwi;
}
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
}
This Class initialises the NewBeautifulKiwi, creating the database Tables and Prints the inserted data to screen:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "KIWI_TABLE")
public class NewBeautifulKiwi implements Serializable {
#Id
#GeneratedValue
private int KiwiId;
private String Kiwi;
public int getKiwiId() {
return KiwiId;
}
public void setKiwiId(int KiwiId) {
this.KiwiId = KiwiId;
}
public String getKiwi() {
return Kiwi;
}
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
}
I'd like to have what's printed on screen displayed in a TableView.
Any help would be great. I will be grateful for any help I can get. Thank you in advance.
try this..
i am creating table and column in scene builder
#FXML
private TableView<PoJoName> table;
#FXML
private TableColumn<PoJoName, Integer> col1;
#FXML
private TableColumn<PoJoName, String> col2;
public ObservableList<PoJoName> data;
#FXML
void initialize()
{
col1.setCellValueFactory(new PropertyValueFactory<PoJoName,Integer>("id")); // here id is a variable name which is define in pojo.
col2.setCellValueFactory(new PropertyValueFactory<PoJoName,String>("name"));
data = FXCollections.observableArrayList();
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sess =sf.openSession();
Query qee = sess.createQuery("from PoJoName");
Iterator ite =qee.iterate();
while(ite.hasNext())
{
PoJoName obj = (PoJoName)ite.next();
data.add(obj);
}
table.setItems(data);
}
You need to define a data model for TableView.
Read section "Defining the Data Model" here: http://docs.oracle.com/javafx/2/ui_controls/table-view.htm

Categories