Java WebService client wrongly generated - java

Well, first, sorry for my bad english.
I'm having a problem when generating a webservice.
I have my lib model, which contains the classes Endereco, Cidade e Cliente, and my DAO lib, which contains the database access classes for these models.
In Endereco.java class I have a private attribute Cidade cidade.
I have gotten a webservice to be a control between front end and back end.
The problem is that when I generate this webservice class "address" gets the int attribute city and not the attribute of my base class "Cidade".
Follow the codes of classes:
"ENDERECO.java":
package lib.modelo;
public class Endereco {
private int id;
private Cliente cliente;
private String endereco;
private String numero;
private String complemento;
private Cidade cidade;
private String bairro;
private String uf;
private String cep;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
}
"CIDADE.java":
package lib.modelo;
public class Cidade {
private int id;
private String descricao;
private double valor_taxa;
public double getValor_taxa() {
return valor_taxa;
}
public void setValor_taxa(double valor_taxa) {
this.valor_taxa = valor_taxa;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
"ENDERECODAO.java":
package lib.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lib.banco.ConexaoBanco;
import lib.modelo.Endereco;
public class EnderecoDAO {
private static final String CONSULTA_POR_ID = "SELECT * FROM cadastros.cliente_endereco WHERE id = ?;";
private static final String CONSULTA_POR_CLIENTE = "SELECT * FROM cadastros.cliente_endereco WHERE fK_cliente = ?;";
private static final String INSERE = "INSERT INTO cadastros.cliente_endereco ( fk_cliente , endereco , numero , complemento , fk_cidade , bairro , uf , cep) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? );";
private static final String ALTERA = "UPDATE cadastros.cliente_endereco SET endereco = ?, numero = ?, complemento = ?, fk_cidade = ?, bairro = ?, uf = ?, cep = ? WHERE fk_cliente = ? AND id = ?;";
public List<Endereco> ConsultarEnderecoPorCliente (int codCliente) throws SQLException{
Connection conexaoSQL = null;
ResultSet rsEndereco = null;
List<Endereco> listaEndereco = new ArrayList<Endereco>();
ClienteDAO clienteDAO = new ClienteDAO();
CidadeDAO cidadeDAO = new CidadeDAO();
try{
conexaoSQL = ConexaoBanco.getConexao("selecao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(CONSULTA_POR_CLIENTE);
pstmt.setInt(1, codCliente);
rsEndereco = pstmt.executeQuery();
while (rsEndereco.next()){
Endereco endereco = new Endereco();
endereco.setId(rsEndereco.getInt("id"));
endereco.setCliente(clienteDAO.CousultaPorId(rsEndereco.getInt("fk_cliente")));
endereco.setEndereco(rsEndereco.getString("endereco"));
endereco.setNumero(rsEndereco.getString("numero"));
endereco.setComplemento(rsEndereco.getString("complemento"));
endereco.setCidade(cidadeDAO.consultaPorId(rsEndereco.getInt("fk_cidade")));
endereco.setBairro(rsEndereco.getString("bairro"));
endereco.setUf(rsEndereco.getString("uf"));
endereco.setCep(rsEndereco.getString("cep"));
listaEndereco.add(endereco);
}
rsEndereco.close();
conexaoSQL.close();
}catch(Exception e){
conexaoSQL.close();
throw new RuntimeException(e);
}
return listaEndereco;
}
public boolean CadastrarEndereco (Endereco endereco) throws SQLException{
boolean status = false;
Connection conexaoSQL = null;
try {
conexaoSQL = ConexaoBanco.getConexao("insercao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(INSERE);
pstmt.setInt(1, endereco.getCliente().getId());
pstmt.setString(2, endereco.getEndereco());
pstmt.setString(3, endereco.getNumero());
pstmt.setString(4, endereco.getComplemento());
pstmt.setInt(5, endereco.getCidade().getId());
pstmt.setString(6, endereco.getBairro());
pstmt.setString(7, endereco.getUf());
pstmt.setString(8, endereco.getCep());
pstmt.execute();
conexaoSQL.close();
status = true;
} catch (Exception e) {
conexaoSQL.close();
throw new RuntimeException(e);
}
return status;
}
public boolean AlterarEndereco (Endereco endereco) throws SQLException{
boolean status = false;
Connection conexaoSQL = null;
try {
conexaoSQL = ConexaoBanco.getConexao("alteracao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(ALTERA);
pstmt.setString(1, endereco.getEndereco());
pstmt.setString(2, endereco.getNumero());
pstmt.setString(3, endereco.getComplemento());
pstmt.setInt(4, endereco.getCidade().getId());
pstmt.setString(5, endereco.getBairro());
pstmt.setString(6, endereco.getUf());
pstmt.setString(7, endereco.getCep());
pstmt.setInt(8, endereco.getCliente().getId());
pstmt.setInt(9, endereco.getId());
pstmt.execute();
conexaoSQL.close();
pstmt.close();
status = true;
} catch (Exception e) {
conexaoSQL.close();
throw new RuntimeException(e);
}
return status;
}
public Endereco ConsultarEnderecoPorId (int codEndereco) throws SQLException{
Connection conexaoSQL = null;
ResultSet rsEndereco = null;
Endereco endereco = new Endereco();
CidadeDAO cidadeDAO = new CidadeDAO();
ClienteDAO clienteDAO = new ClienteDAO();
try {
conexaoSQL = ConexaoBanco.getConexao("selecao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(CONSULTA_POR_ID);
pstmt.setInt(1, codEndereco);
rsEndereco = pstmt.executeQuery();
if(rsEndereco.next()){
endereco.setBairro(rsEndereco.getString("bairro"));
endereco.setCep(rsEndereco.getString("cep"));
endereco.setCidade(cidadeDAO.consultaPorId(rsEndereco.getInt("fk_cidade")));
endereco.setCliente(clienteDAO.CousultaPorId(rsEndereco.getInt("fk_cliente")));
endereco.setComplemento(rsEndereco.getString("complemento"));
endereco.setEndereco(rsEndereco.getString("endereco"));
endereco.setId(rsEndereco.getInt("id"));
endereco.setNumero(rsEndereco.getString("numero"));
endereco.setUf(rsEndereco.getString("uf"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
conexaoSQL.close();
rsEndereco.close();
return endereco;
}
}
And the WebService for ENDERECO "SERVICOENDERECO.java":
package lib.webservice.endereco;
import java.util.ArrayList;
import java.util.List;
import lib.dao.EnderecoDAO;
import lib.modelo.Cidade;
import lib.modelo.Cliente;
import lib.modelo.Endereco;
public class ServicoEndereco {
public Endereco[] consultaPorCliente(int id){
EnderecoDAO eDAO = new EnderecoDAO();
List< Endereco > listaEndereco = new ArrayList<Endereco>();
try{
listaEndereco = eDAO.ConsultarEnderecoPorCliente( id );
}catch(Exception e){
throw new RuntimeException(e);
}
return listaEndereco.toArray( new Endereco[0] );
}
public boolean cadastra( Cliente cliente , String logradouro , String numero ,
String complemento , Cidade cidade , String bairro ,
String uf , String cep){
boolean status = false;
try{
Endereco endereco = new Endereco();
EnderecoDAO eDAO = new EnderecoDAO();
endereco.setCliente(cliente);
endereco.setEndereco(logradouro);
endereco.setNumero(numero);
endereco.setComplemento(complemento);
endereco.setCidade(cidade);
endereco.setBairro(bairro);
endereco.setUf(uf);
endereco.setCep(cep);
status = eDAO.CadastrarEndereco(endereco);
}catch(Exception e){
throw new RuntimeException(e);
}
return status;
}
public boolean altera(Cliente cliente , String logradouro , String numero ,
String complemento , Cidade cidade , String bairro ,
String uf , String cep , int id){
boolean status = false;
try{
Endereco endereco = new Endereco();
EnderecoDAO eDAO = new EnderecoDAO();
endereco.setCliente(cliente);
endereco.setEndereco(logradouro);
endereco.setNumero(numero);
endereco.setComplemento(complemento);
endereco.setCidade(cidade);
endereco.setBairro(bairro);
endereco.setUf(uf);
endereco.setCep(cep);
endereco.setId(id);
status = eDAO.AlterarEndereco(endereco);
}catch(Exception e){
throw new RuntimeException(e);
}
return status;
}
public Endereco consultaPorId (int id){
EnderecoDAO eDAO = new EnderecoDAO();
Endereco endereco = new Endereco();
try {
endereco = eDAO.ConsultarEnderecoPorId(id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return endereco;
}
}

Problem solved!
The difference between the classes was taking place due to my server configuration. When I updated the .jar files from the apache server classpath the code was generated properly.

Related

Trying to display all data from database table into Jtable using reflection

I'm trying to display all the data from different database table into a JTable using reflection but when i run the code I gen this kind of error:. The methods responsible for that are createViewAllQuery, ViewAll and createObjects from AbstractDAO class.
Any idea what the problem is? Thanks!
package project3;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.jdbc.PreparedStatement;
public class AbstractDAO<T>{
protected static final Logger LOGGER = Logger.getLogger(AbstractDAO.class.getName());
private final Class<T> type;
#SuppressWarnings("unchecked")
public AbstractDAO() {
this.type = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
private String createFindQuery(String field) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
sb.append(" * ");
sb.append(" FROM ");
sb.append(type.getSimpleName());
sb.append(" WHERE " + field + "=?");
return sb.toString();
}
private String createAddQuery(T object) throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(type.getSimpleName());
sb.append(" VALUES (");
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
if(field.get(object) instanceof Integer) {
sb.append(field.get(object));
sb.append(",");
}
else {
sb.append("'");
sb.append(field.get(object));
sb.append("',");
}
}
sb.deleteCharAt(sb.length()-1);
sb.append(");");
System.out.println(sb.toString());
return sb.toString();
}
private String createViewAllQuery() throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ");
sb.append(type.getSimpleName());
sb.append(";");
return sb.toString();
}
public List<T> ViewAll() throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createViewAllQuery();
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public JTable createTable(List<T> objects) throws IllegalArgumentException, IllegalAccessException {
ArrayList<String> columnNamesArrayList = new ArrayList<String>();
for(Field field : objects.get(0).getClass().getDeclaredFields()) {
field.setAccessible(true);
columnNamesArrayList.add(field.getName());
}
String[] columnNames = new String[columnNamesArrayList.size()];
columnNames = columnNamesArrayList.toArray(columnNames);
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
Iterator<T> i = objects.iterator();
while(i.hasNext()) {
T object = i.next();
ArrayList<Object> columnDataAsArrayList = new ArrayList<Object>();
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
columnDataAsArrayList.add(field.get(object));
}
Object[] columnDataAsArray = new Object[columnDataAsArrayList.size()];
columnDataAsArray = columnDataAsArrayList.toArray(columnDataAsArray);
tableModel.addRow(columnDataAsArray);
}
JTable table = new JTable(tableModel);
return table;
}
public void add(T object) throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
String query = createAddQuery(object);
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.executeUpdate();
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
}
public List<T> findByFirstName(String firstName) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("first_name");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, firstName);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public T findById(int id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("id");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setInt(1, id);
resultSet = statement.executeQuery();
return createObjects(resultSet).get(0);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findById " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
private List<T> createObjects(ResultSet resultSet){
List<T> list = new ArrayList<T>();
try {
try {
while(resultSet.next()) {
T instance = type.newInstance();
for(Field field: type.getDeclaredFields()) {
Object value = resultSet.getObject(field.getName());
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
Method method = propertyDescriptor.getWriteMethod();
method.invoke(instance, value);
}
list.add(instance);
}
} catch (IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException | SQLException | IntrospectionException e) {
e.printStackTrace();
}
}catch(InstantiationException e) {
e.printStackTrace();
}
return list;
}
}
package project3;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.html.HTMLDocument.Iterator;
public class ProductsDAO extends AbstractDAO<Products>{
public ProductsDAO() {};
public static void main(String[] args) {
ProductsDAO p1 = new ProductsDAO();
//Products product1 = new Products(3, "cascaval", 5, " tip de branza facuta din lapte de vaca sau oaie", 4680);
try {
JTable table = new JTable();
table = p1.createTable(p1.ViewAll());
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
/*List<Products> list = new ArrayList<Products>();
list = p1.ViewAll();
java.util.Iterator<Products> i = list.iterator();
while(i.hasNext()) {
Products x = i.next();
System.out.println(x.getDescription());
}*/
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Here is one of the classes:
package project3;
public class Products {
private int id;
private String name;
private int price;
private String description;
private int stoc;
public Products(int id, String name, int price, String description, int stoc) {
super();
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.stoc = stoc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getStoc() {
return stoc;
}
public void setStoc(int stoc) {
this.stoc = stoc;
}
}
Your class Products hasn't got a default-constructor (so no method <init>), but you're trying to use that in
T instance = type.newInstance();
Since the Method isn't there the NoSuchMethodException is thrown.
You either have to add a default-constructor like
public Products() {
...
}
or call the constructor with arguments (probably harder to do ;)

Java, Swing - Jtable row remain after delete

I have a JTable that displays data from mysql, the code below is works (can insert, update, delete) But if I delete a row and create another with the same id, the previous data in the row (before I delete it) appears instead of new data.
code for insert and delete
private void simpanBtnActionPerformed(java.awt.event.ActionEvent evt) {
String hantaranID = hantaranIDText.getText();
String namaLengkap = namaLengkapET.getText();
String alamat = jTextArea1.getText();
String hp = noHp.getText();
Date pengambilan = jXDatePicker1.getDate();
Date pengembalian = jXDatePicker2.getDate();
if (hantaranID.isEmpty()){
JOptionPane.showMessageDialog(null, "Hantaran ID tidak boleh kosong.");
} else if (namaLengkap.isEmpty()){
JOptionPane.showMessageDialog(null, "Nama lengkap tidak boleh kosong.");
} else if (alamat.isEmpty()) {
JOptionPane.showMessageDialog(null, "Alamat tidak boleh kosong.");
} else if (hp.isEmpty()){
JOptionPane.showMessageDialog(null, "Nomor Hand Phone tidak boleh kosong.");
} else if (pengambilan != null && pengembalian != null){
try {
DateFormat sysDate = new SimpleDateFormat("yyyy/MM/dd");
String tglPengambilan = sysDate.format(jXDatePicker1.getDate()).toString();
String tglPengembalian = sysDate.format(jXDatePicker2.getDate()).toString();
Connection conn = MyDBConnection.getConnection();
String insert = "insert into hantaran (hantaran_id, nama_lengkap, alamat, no_hp, tgl_pengambilan, tgl_pengembalian)"
+ "values (?, ?, ? , ? , ?, ?)";
PreparedStatement insertHantaran = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
insertHantaran.setString(1, hantaranID);
insertHantaran.setString(2, namaLengkap);
insertHantaran.setString(3, alamat);
insertHantaran.setString(4, hp);
insertHantaran.setString(5, tglPengambilan);
insertHantaran.setString(6, tglPengembalian);
insertHantaran.executeUpdate();
hantaranTabel.revalidate();
hantaranList.clear();
hantaranList.addAll( hantaranQuery.getResultList());
hantaranIDText.setText("");
namaLengkapET.setText("");
jTextArea1.setText("");
noHp.setText("");
jXDatePicker1.setDate(null);
jXDatePicker2.setDate(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Tanggal Pengambilan dan Pengembalian tidak boleh kosong.");
}
// TODO add your handling code here:
}
private void hapusBtnActionPerformed(java.awt.event.ActionEvent evt) {
String id = hantaranIDText.getText();
Object[] options = { "YA", "Tidak" };
int choice = JOptionPane.showOptionDialog(null,
"Hapus data ini??",
"Hapus..!",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (choice == JOptionPane.YES_OPTION){
try {
Connection conn = MyDBConnection.getConnection();
String reqq = "DELETE FROM hantaran WHERE hantaran_id = ?";
PreparedStatement delete = conn.prepareStatement(reqq);
delete.setString(1, id);
delete.executeUpdate();
hantaranTabel.revalidate();
hantaranList.clear();
hantaranList.addAll( hantaranQuery.getResultList());
editBtn.setText("EDIT");
hantaranIDText.setText("");
namaLengkapET.setText("");
jTextArea1.setText("");
noHp.setText("");
jXDatePicker1.setDate(null);
jXDatePicker2.setDate(null);
hapusBtn.setEnabled(false);
simpanBtn.setEnabled(true);
} catch (Exception ex) {
Logger.getLogger(HennaPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
my class
package aplikasi_mahar;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.Date;
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.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
/**
*
* #author User
*/
#Entity
#Table(name = "hantaran", catalog = "mahardb", schema = "")
#NamedQueries({
#NamedQuery(name = "Hantaran.findAll", query = "SELECT h FROM Hantaran h"),
#NamedQuery(name = "Hantaran.findByHantaranId", query = "SELECT h FROM Hantaran h WHERE h.hantaranId = :hantaranId"),
#NamedQuery(name = "Hantaran.findByNamaLengkap", query = "SELECT h FROM Hantaran h WHERE h.namaLengkap = :namaLengkap"),
#NamedQuery(name = "Hantaran.findByAlamat", query = "SELECT h FROM Hantaran h WHERE h.alamat = :alamat"),
#NamedQuery(name = "Hantaran.findByNoHp", query = "SELECT h FROM Hantaran h WHERE h.noHp = :noHp"),
#NamedQuery(name = "Hantaran.findByTglPengambilan", query = "SELECT h FROM Hantaran h WHERE h.tglPengambilan = :tglPengambilan"),
#NamedQuery(name = "Hantaran.findByTglPengembalian", query = "SELECT h FROM Hantaran h WHERE h.tglPengembalian = :tglPengembalian")})
public class Hantaran 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 = "hantaran_id")
private Integer hantaranId;
#Basic(optional = false)
#Column(name = "nama_lengkap")
private String namaLengkap;
#Basic(optional = false)
#Column(name = "alamat")
private String alamat;
#Basic(optional = false)
#Column(name = "no_hp")
private String noHp;
#Basic(optional = false)
#Column(name = "tgl_pengambilan")
#Temporal(TemporalType.DATE)
private Date tglPengambilan;
#Basic(optional = false)
#Column(name = "tgl_pengembalian")
#Temporal(TemporalType.DATE)
private Date tglPengembalian;
public Hantaran() {
}
public Hantaran(Integer hantaranId) {
this.hantaranId = hantaranId;
}
public Hantaran(Integer hantaranId, String namaLengkap, String alamat, String noHp, Date tglPengambilan, Date tglPengembalian) {
this.hantaranId = hantaranId;
this.namaLengkap = namaLengkap;
this.alamat = alamat;
this.noHp = noHp;
this.tglPengambilan = tglPengambilan;
this.tglPengembalian = tglPengembalian;
}
public Integer getHantaranId() {
return hantaranId;
}
public void setHantaranId(Integer hantaranId) {
Integer oldHantaranId = this.hantaranId;
this.hantaranId = hantaranId;
changeSupport.firePropertyChange("hantaranId", oldHantaranId, hantaranId);
}
public String getNamaLengkap() {
return namaLengkap;
}
public void setNamaLengkap(String namaLengkap) {
String oldNamaLengkap = this.namaLengkap;
this.namaLengkap = namaLengkap;
changeSupport.firePropertyChange("namaLengkap", oldNamaLengkap, namaLengkap);
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
String oldAlamat = this.alamat;
this.alamat = alamat;
changeSupport.firePropertyChange("alamat", oldAlamat, alamat);
}
public String getNoHp() {
return noHp;
}
public void setNoHp(String noHp) {
String oldNoHp = this.noHp;
this.noHp = noHp;
changeSupport.firePropertyChange("noHp", oldNoHp, noHp);
}
public Date getTglPengambilan() {
return tglPengambilan;
}
public void setTglPengambilan(Date tglPengambilan) {
Date oldTglPengambilan = this.tglPengambilan;
this.tglPengambilan = tglPengambilan;
changeSupport.firePropertyChange("tglPengambilan", oldTglPengambilan, tglPengambilan);
}
public Date getTglPengembalian() {
return tglPengembalian;
}
public void setTglPengembalian(Date tglPengembalian) {
Date oldTglPengembalian = this.tglPengembalian;
this.tglPengembalian = tglPengembalian;
changeSupport.firePropertyChange("tglPengembalian", oldTglPengembalian, tglPengembalian);
}
#Override
public int hashCode() {
int hash = 0;
hash += (hantaranId != null ? hantaranId.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 Hantaran)) {
return false;
}
Hantaran other = (Hantaran) object;
if ((this.hantaranId == null && other.hantaranId != null) || (this.hantaranId != null && !this.hantaranId.equals(other.hantaranId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "aplikasi_mahar.Hantaran[ hantaranId=" + hantaranId + " ]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
connection class
public class MyDBConnection {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mahardb", "root", "");
}
return connection;
}
}
Notes : i'm using persistent connection, java jdk7
You have to set new Data for your TableModel or remove deleted Data/Row from TableModel and call fireTableDataChanged method:
yourTableModel.setData(getYourData());
yourTableModel.fireTableDataChanged();

Can't get ComboboxTableCell in javafx app

I am trying to show a combobox for each record that is fetched from database,but unfortunatley i can't get any combobox in expected column.
Here is code for my model class:
public class Employee {
private final int id;
private final SimpleStringProperty ename;
private final SimpleStringProperty ecnic;
private final SimpleDoubleProperty ebalance;
private final SimpleDoubleProperty etotalpaid;
private SimpleStringProperty estatus;
public Employee(int id, String ename, String ecnic, Double ebalance,
Double etotalpaid, String estatus) {
super();
this.id = id;
this.ename = new SimpleStringProperty(ename);
this.ecnic = new SimpleStringProperty(ecnic);
this.ebalance = new SimpleDoubleProperty(ebalance);
this.etotalpaid = new SimpleDoubleProperty(etotalpaid);
this.estatus = new SimpleStringProperty(estatus);
}
public String getEstatusproperty() {
return estatus.get();
}
public String getEstatus() {
return estatus.get();
}
public void setEstatus(String estatus) {
this.estatus = new SimpleStringProperty(estatus);
}
public int getId() {
return id;
}
public String getEname() {
return ename.get();
}
public String getEcnic() {
return ecnic.get();
}
public Double getEbalance() {
return ebalance.get();
}
public Double getEtotalpaid() {
return etotalpaid.get();
}
}
Here is code for my method that i call to fetch data from database..
public void attendence() throws SQLException{
employeelist = FXCollections.observableArrayList();
ename.setCellValueFactory(new PropertyValueFactory<Employee,String>("ename"));
ecnic.setCellValueFactory(new PropertyValueFactory<Employee,String>("ecnic"));
ebalance.setCellValueFactory(new PropertyValueFactory<Employee,Double>("ebalance"));
etotalpaid.setCellValueFactory(new PropertyValueFactory<Employee,Double>("etotalpaid"));
estatus.setCellValueFactory(new PropertyValueFactory<Employee,String>("estatus"));
estatus.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), attendenceoptions));
estatus.setOnEditCommit(
new EventHandler<CellEditEvent<Employee, String>>() {
#Override
public void handle(CellEditEvent<Employee, String> t) {
((Employee) t.getTableView().getItems().get(t.getTablePosition().getRow())).setEstatus(t.getNewValue());
};
});
estatus.setEditable(true);
stmt = conn.createStatement();
sql = "select * from employe";
rs = stmt.executeQuery(sql);
while(rs.next()){
employeelist.add(new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDouble(5),rs.getDouble(6),"Present"));
employeetable.setItems(employeelist);
}
stmt.close();
rs.close();
}
}
Added this in method to solve issue.
employeetable.setEditable(true);

JAVA linking ID to name from other table

I got a tableview with a tablecolumn ("ID").
How can i link the ID to show the value?
For example: ID 90 has to be "Shop" and ID 91 has to be "Wallmart"..
I'm using 2 tables:
Person(id, personName, personShopID)
Items(id, shopName)
PersonShopID links to ITEMS id and i have to show the shopName instead of the ID..
Note: I'm using JavaFX and i'm getting data from mysql database and i'm using tcShopName.setCellValueFactory(new PropertyValueFactory<>("personShopID"));
kind regards !
package databag;
import java.sql.Timestamp;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import vivesgoal.controller.CustomDate;
/**
*
* #author Lowie Menu
*/
public class PersoonBag {
private int id;
private String naam;
private String voornaam;
private Date geboortedatum;
private String opmerking;
private boolean isTrainer;
private int ploeg_id;
public PersoonBag(int id, String naam, String voornaam, Date geboortedatum, String opmerking,boolean isTrainer, int ploeg_id){
this.id=id;
this.naam=naam;
this.voornaam=voornaam;
this.geboortedatum=geboortedatum;
this.opmerking=opmerking;
this.isTrainer=isTrainer;
this.ploeg_id=ploeg_id;
}
public PersoonBag()
{
}
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public String getVoornaam() {
return voornaam;
}
public Date getGeboortedatum() {
return geboortedatum;
}
public String getGeboortedatumAlter(){
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String datum = df.format(geboortedatum);
return datum;
}
public CustomDate getMyDate(){
return new CustomDate(geboortedatum.getTime());
}
public java.util.Date getGeboortedatumUtil(){
return geboortedatum;
}
public String getOpmerking() {
return opmerking;
}
public boolean isIsTrainer() {
return isTrainer;
}
public int getPloeg_id() {
return ploeg_id;
}
public void setId(int id) {
this.id = id;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setVoornaam(String voornaam) {
this.voornaam = voornaam;
}
public void setGeboortedatum(Date geboortedatum) {
this.geboortedatum =geboortedatum;
}
public void setOpmerking(String opmerking) {
this.opmerking = opmerking;
}
public void setIsTrainer(boolean isTrainer) {
this.isTrainer = isTrainer;
}
public void setPloeg_id(int ploeg_id) {
this.ploeg_id = ploeg_id;
}
}
and class Team (dutch ploeg)
package databag;
/**
*
* #author Lowie Menu
*/
public class PloegBag {
private int id;
private String naam;
private String niveau;
private int trainer_id;
public PloegBag(int id, String naam, String niveau, int trainer_id){
this.id = id;
this.naam = naam;
this.niveau = niveau;
this.trainer_id = trainer_id;
}
public PloegBag(){
}
public void setId(int id) {
this.id = id;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setNiveau(String niveau) {
this.niveau = niveau;
}
public void setTrainer_id(int trainer_id){
this.trainer_id=trainer_id;
}
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public String getNiveau() {
return niveau;
}
public int getTrainer_id(){
return trainer_id;
}
}
Note: i'm trying to link ploeg_id from PersoonBag to the name of PloegBag(ploegnaam).
This sql code gets me the name of the club matching the id
select * from persoon AS p INNER JOIN ploeg AS ploeg ON p.ploeg_id =ploeg.id where ploeg.naam=?"
Update: no value in ploeg.naam? maybe issue here
p
ublic ArrayList<PersoonBag> zoekAlleSpelers() throws DBException, ApplicationException {
ArrayList<PersoonBag> pb = new ArrayList<>();
try (Connection conn = ConnectionManager.getConnection();) {
try(PreparedStatement stmt = conn.prepareStatement(
"select * from persoon inner join ploeg where persoon.ploeg_id = ploeg.id");) {
// execute voert elke sql-statement uit, executeQuery enkel de eenvoudige
stmt.execute();
// result opvragen (en automatisch sluiten)
try (ResultSet rs = stmt.getResultSet()) {
// van alle rekennigen uit de database,
// RekeningBag-objecten maken en in een RekeningVector steken
while (rs.next()) {
PersoonBag p = new PersoonBag();
PloegBag ploeg = new PloegBag();
// ploeg.setId(rs.getInt("id"));
ploeg.setNaam(rs.getString("naam"));
p.setId(rs.getInt("id"));
p.setNaam(rs.getString("naam"));
p.setVoornaam(rs.getString("voornaam"));
p.setGeboortedatum(rs.getDate("geboortedatum"));
p.setOpmerking(rs.getString("opmerking"));
p.setIsTrainer(rs.getBoolean("isTrainer"));
p.setPloeg_id(ploeg);
pb.add(p);
}
return pb;
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - resultset");
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - statement");
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - connection");
}
}
Still have'nt found the issue.. this is function to store the data from the sql query in the table note: this works only ploegname isn't showing
PersoonDB pdb = new PersoonDB();
ArrayList<PersoonBag> persoonbag = new ArrayList<>();
try {
ArrayList<PersoonBag> spelersLijst = pdb.zoekAlleSpelers();
for (PersoonBag r : spelersLijst) {
PersoonBag speler = new PersoonBag(r.getId(),r.getNaam(), r.getVoornaam(),r.getMyDate(),r.getOpmerking(), r.isIsTrainer(),r.getPloeg_id());
persoonbag.add(speler);
}
ObservableList<PersoonBag> spelers = FXCollections.observableArrayList(persoonbag);
taSpelers.setItems(spelers);
Cell items:
#FXML
private TableView<PersoonBag> taSpelers;
#FXML
private TableColumn tcFamilienaam;
#FXML
private TableColumn tcVoornaam;
#FXML
private TableColumn tcOpmerking;
#FXML
private TableColumn<PersoonBag, CustomDate> tcGeboortedatum;
#FXML
private TableColumn<PersoonBag, PloegBag> tcPloeg;
#Override
public void initialize(URL url, ResourceBundle rb) {
tcFamilienaam.setCellValueFactory(new PropertyValueFactory<>("naam"));
tcVoornaam.setCellValueFactory(new PropertyValueFactory<>("voornaam"));
tcGeboortedatum.setCellValueFactory(new PropertyValueFactory<PersoonBag, CustomDate>("geboortedatum"));
tcOpmerking.setCellValueFactory(new PropertyValueFactory<>("opmerking"));
tcPloeg.setCellValueFactory(new PropertyValueFactory<>("ploeg"));
tcPloeg.setCellFactory(tc -> new TableCell<PersoonBag, PloegBag>() {
#Override
public void updateItem(PloegBag ploeg, boolean empty) {
if (empty || ploeg ==null){
setText("");
} else{
setText(ploeg.getNaam());
}
}
});
UPDATE!!! i'm almost there! It's getting the 'naam' data from persoon instead of 'naam' from ploeg!
issue:
while (rs.next()) {
PloegBag ploeg = new PloegBag();
ploeg.setId(rs.getInt("id"));
ploeg.setNaam(rs.getString("naam"));
PersoonBag p = new PersoonBag();
p.setId(rs.getInt("id"));
p.setNaam(rs.getString("naam"));
p.setVoornaam(rs.getString("voornaam"));
p.setGeboortedatum(rs.getDate("geboortedatum"));
p.setOpmerking(rs.getString("opmerking"));
p.setIsTrainer(rs.getBoolean("isTrainer"));
p.setPloeg(ploeg);
pb.add(p);
}
when i'm putting niveau instead of 'naam' it's get me the correct matching result! now i need the name..!
Instead of storing the id of the linked item, store a reference to the item itself. So your PersoonBag class will look like:
public class PersoonBag {
private int id;
private String naam;
private String voornaam;
private Date geboortedatum;
private String opmerking;
private boolean isTrainer;
private PloegBag ploeg;
public PersoonBag(int id, String naam, String voornaam, Date geboortedatum, String opmerking,boolean isTrainer, PloegBag ploeg){
this.id=id;
this.naam=naam;
this.voornaam=voornaam;
this.geboortedatum=geboortedatum;
this.opmerking=opmerking;
this.isTrainer=isTrainer;
this.ploeg=ploeg;
}
public PersoonBag()
{
}
public PloegBag getPloeg() {
return ploeg ;
}
public void setPloeg(PloegBag ploeg) {
this.ploeg = ploeg ;
}
// other get/set methods ...
}
Now you can load everything at once using an inner join in the SQL:
String sql = "select * from persoon inner join ploeg where persoon.ploeg_id = ploeg.id";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
List<Persoon> persoonList = new ArrayList<>();
while (rs.next()) {
PloegBag ploeg = new PloegBag();
// populate ploeg with data from rs...
PersoonBag persoon = new PersoonBag();
persoon.setPloeg(ploeg);
// populate persoon with remaining data from rs...
persoonList.add(persoon);
}
(Obviously you can modify the SQL code, e.g. to retrieve specific items from the database, or just generally to improve it, etc.)
Now your JavaFX code looks like:
TableView<PersoonBag> persoonTable = new TableView<>();
TableColumn<PersoonBag, PloegBag> tcPloeg = new TableColumn<>("Ploeg");
tcPloeg.setCellValueFactory(new PropertyValueFactory<>("ploeg"));
// other columns...
To get the cells to display the value you need from the PloegBag, there are two ways. The "quick and dirty" way is just to define a toString() method in the PloegBag class:
public class PloegBag {
// ...
#Override
public String toString() {
return naam ;
}
}
This isn't very satisfactory, though, as you might want to toString() method to do something else for other reasons in your application. The "proper" way is to use a cell factory:
tcPloeg.setCellFactory(tc -> new TableCell<PersoonBag, PloegBag>() {
#Override
public void updateItem(PloegBag ploeg, boolean empty) {
if (empty || ploeg == null) {
setText(null);
} else {
setText(ploeg.getNaam());
}
}
});
1) establish a Connection to your database from your Java-program by using JDBC:
private static Connection getDBConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?autoReconnect=true&user=myUser&password=myPass");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error on getDBCOnnection "+e.toString());
}
return connection;
}
2) Query your Items table in a query like this:
SELECT shopName FROM Items WHERE ID = 90
Java:
public static ResultSet runQuery(String query) {
if(conn == null){
conn = getDBConnection();
}
Statement stmt;
ResultSet rs;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
return rs;
} catch (SQLException e) {
System.out.println(e + " " + e.getMessage());
return null;
}
}
3) Read the result
ResultSet rs = runQuery(query);
String result = rs.getString(1);
Hibernate could do it all for you, including queries... just saying... Although steep learning curve if doing it for the first time... You need to model your container object to have these fields, for example person would have:
class Person{
long id;
String name;
String shopName;
...
}
Then in your data service (provider of data) you would query for that, lets say:
SELECT p.id, p.name, s.name
FROM person p, shop s
WHERE p.shopId = s.shopId;
and provide simple rowmapper
#Ovrride
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person(rs.getInt("personId"), rs.getString("personName"), rs.getString("shopName"));
return person;
}
You end up with list of Persons, which you can operate on within app. As someone mentioned earlier, you would want to do this, beforehand. Every time you need that list you would hit a local cache, instead of going back to DB. You could set a policy to refresh cache if needed.

What is the logic of creating the Mysql SELECT Statement for drop down in Struts + JSP?

can you please help me rectify the code below, I'm trying to create a populated drop down list in struts 2 in Eclipse as my IDE. This is my first time to use 'STRUTS' as well as 'IDE ECLIPSE'.
To be specific by the SELECT statement I do not know how to write the code that, when a user selects the 'Make' of the car, the database extracts the different 'Models' of that make. But other select items like 'Color', should be optional in that a user can proceed to search for the 'Make' minus choosing an option from them.
Please help I'm new in ActionClass and DataBase. Thanx in advance.
package drive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class CarSearch extends ActionSupport {
private String model;
private String modification;
private String engine;
private String color;
private String bodyType;
private String minPrice;
private String maxPrice;
private String mileage;
private int minYear;
private int maxYear;
private String make;
public String execute () {
String ret = NONE;
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost/Cars";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "root", "$jademedia247");
String sql = "SELECT make FROM type WHERE";
sql+=" model = ? AND modification = ? ";
PreparedStatement ps = conn.prepareStatement (sql);
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
while (rs.next()){
make = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) {
ret = ERROR;
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return ret;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModification() {
return modification;
}
public void setModification (String modification) {
this.modification = modification;
}
public String getEngine() {
return engine;
}
public void setEngine (String engine) {
this.engine = engine;
}
public String getColor() {
return color;
}
public void setColor (String color) {
this.color = color;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getMinPrice() {
return minPrice;
}
public void setMinPrice(String minPrice) {
this.minPrice = minPrice;
}
public String getMaxPrice () {
return maxPrice;
}
public void setMaxPrice (String maxPrice) {
this.maxPrice = maxPrice;
}
public String getMileage () {
return mileage;
}
public void setMileage (String mileage) {
this.mileage = mileage ;
}
public int getMinYear() {
return minYear;
}
public void setMinYear(int minYear) {
this.minYear = minYear;
}
public int getMaxYear() {
return maxYear;
}
public void setMaxYear(int maxYear) {
this.maxYear = maxYear;
}
public String getMake() {
return make;
}
public void setMake(String make){
this.make = make;
}
}
PreparedStatement ps = conn.prepareStatement ("SELECT field_name FROM table_name WHERE model = ? AND modification = ? ");
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
//it will help you

Categories