How to draw database Table items onto a TableView using hibernate - java

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

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

Detached entity is not being merged correctly?

i need some help, my code is below.
#Override
public SEDocumentListWidget clone() throws CloneNotSupportedException {
final SEDocumentListWidget clone = (SEDocumentListWidget) super.clone();
final Set<SEDocumentListCategoryList> listCopy = new HashSet<>(clone.getDocumentListCategoryList());
SEEntityManager.flush();
SEEntityManager.detach(listCopy);
for (SEDocumentListCategoryList listItem: listCopy) {
listItem.setOid(UUID.randomUUID().toString());
}
final Set<SEDocumentListCategoryList> listCopyMerged = SEEntityManager.getEntityManager().merge(listCopy);
clone.setDocumentListCategoryList(listCopyMerged);
return clone;
}
When i run it, it throws the following error:
Caused by: org.hibernate.PersistentObjectException: detached entity
passed to persist: com.softexpert.dashboard.entity.SEDashboard
It might be something very simple, any help would be appreciated, it also looks like a specific problem with this line:
final Set<SEDocumentListCategoryList> listCopyMerged = SEEntityManager.getEntityManager().merge(listCopy);
#EDIT Added the SEDocumentListCategoryList entity
package com.softexpert.dashboard.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.softexpert.platform.annotation.Audit;
import com.softexpert.platform.artefacts.EntityObject;
/**
*
* #author elia.melfior
*
*/
#Entity
#Audit(dataChange = true, dataLoad = false)
#Table(name = "SEDOCUMENTLISTCATEGORYLIST")
public class SEDocumentListCategoryList extends EntityObject {
private static final long serialVersionUID = 1L;
private Integer cdCategory;
#Column(name = "CDCATEGORY")
public Integer getCdCategory() {
return this.cdCategory;
}
public void setCdCategory(Integer cdCategory) {
this.cdCategory = cdCategory;
}
}
Looking at your code I think you want to copy persistent objects and persist them with a new id. In this case, i think you must use persist() instead of merge() (which tries to update your detached entities).

Spring Boot error: Error creating bean with name 'albumController': Unsatisfied dependency expressed through field 'albumService'

I am new to Spring boot. I am trying to create the below service. Parent class is Artists. Child is Album. I am trying to fetch all the Albums corresponding to particular Artists. While creating custom method in crudRepository I am getting error. Can't able to identify the exact issue, help for the error will be greatly appreciated.
Artists.java (Bean class of Parent)
package com.org.Music_App.Artists;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import com.org.Music_App.Albums.Album;
#Entity
public class Artists {
#Id
private int artists_Id;
private String artists_Name;
private int no_of_Albums;
private String debut_Album;
#OneToMany
#JoinColumn(name = "artists_id")
#Transient
private List<Album> album;
public Artists() {
}
public Artists(int artists_Id, String artists_Name, int no_of_Albums, String debut_Album) {
this.artists_Id = artists_Id;
this.artists_Name = artists_Name;
this.no_of_Albums = no_of_Albums;
this.debut_Album = debut_Album;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
public int getNo_of_Albums() {
return no_of_Albums;
}
public void setNo_of_Albums(int no_of_Albums) {
this.no_of_Albums = no_of_Albums;
}
public String getDebut_Album() {
return debut_Album;
}
public void setDebut_Album(String debut_Album) {
this.debut_Album = debut_Album;
}
public List<Album> getAlbum() {
return album;
}
public void setAlbum(List<Album> album) {
this.album = album;
}
}
Album.java (Bean class of Child)
package com.org.Music_App.Albums;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import com.org.Music_App.Artists.Artists;
#Entity
public class Album {
#Id
private int album_Id;
private int artists_Id;
private String album_Name;
private int no_of_Songs;
private String artists_Name;
public Album()
{
}
public Album(int album_Id, int artists_Id, String album_Name, int no_of_Songs, String artists_Name) {
super();
this.album_Id = album_Id;
this.artists_Id = artists_Id;
this.album_Name = album_Name;
this.no_of_Songs = no_of_Songs;
this.artists_Name = artists_Name;
}
public int getAlbum_Id() {
return album_Id;
}
public void setAlbum_Id(int album_Id) {
this.album_Id = album_Id;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getAlbum_Name() {
return album_Name;
}
public void setAlbum_Name(String album_Name) {
this.album_Name = album_Name;
}
public int getNo_of_Songs() {
return no_of_Songs;
}
public void setNo_of_Songs(int no_of_Songs) {
this.no_of_Songs = no_of_Songs;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
}
Custom method:
package com.org.Music_App.Repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.org.Music_App.Albums.Album;
import com.org.Music_App.Artists.Artists;
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
Error:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'albumRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
Can you retry the same code removing all underscores?
Java naming convention use camelcase and Spring assumes conventions in order to wire things properly.
if you have
#Id
private int albumId;
you have:
public int getAlbumId;
public void setAlbumId(int albumId);
etc.
PS: you don't need to define the artistsId property in the Album entity only because there will be an "artistis_id" column in the "album" table.
The AlbumRepository's findByArtists_Id method thinks that it needs to look up data based on artists instead of artist_Id, because it seems to be considering the String after "By" upto the underscore.
Try removing underscore and it may solve your issue.
It seems underscores doesn't work with the entity field names. Here is a similar question, where you can find a detailed answer: Spring-Data-Jpa Repository - Underscore on Entity Column Name
Hope that helps!
You have to define your repository here propertly, add #Repository here
#Repository
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
then it will start working

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;
}
}

JTable TableModel problem in 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.

Categories