0

I have created MySQL DB and a Java GUI app using SWING . I have managed to add data to DB via SWING GUI for some tables but for some that have Foreign keys (at least i think that is why) i cant add data. It is probably something wrong with the FK or the table or with the methods i wrote to add the data to DB...

Here are my model , GUI classes ,MySQL table information and methods i try to use to add data to DB :

Model PRODUCT class :

package myshop.model;
public class Product {
    public int id;
    public String name;
    public Category category;
    public Manufacturer manufacturer;
    public Double price;
    public int quantity;
    public Product(int id,String name,Category category,Manufacturer manufacturer,Double price,int quantity){
        this.id = id;
        this.name = name;
        this.category = category;
        this.manufacturer = manufacturer;
        this.price = price;
        this.quantity = quantity;
    }
    @Override
    public String toString() {
        return this.name;
    }
}

Model CATEGORY class:

package myshop.model;
public class Category {
    public int id;
    public String name;
    public String description;
    public Category(int id,String name,String description){
        this.id = id;
        this.name = name;
        this.description = description;
}
    @Override
    public String toString() {
        return this.name;
    }
}

Model MANUFACTURER class :

package myshop.model;
public class Manufacturer {
    public int id;
    public String name;
    public String description;
    public Manufacturer(int id,String name,String description){
        this.id = id;
        this.name = name;
        this.description = description;
    }
    @Override
    public String toString() {
        return this.name;
    }
}

GUI class where i have created GUI for adding data to DB(questionable code is in jButton1actionpreformed):

    package myshop.gui;
    import java.sql.SQLException;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JOptionPane;
    import myshop.model.Category;
    import myshop.model.Manufacturer;
    import myshop.model.MyShopRepository;
    import myshop.model.Product;

    public class AddProductPanel extends javax.swing.JPanel {

        public AddProductPanel() throws SQLException {
        initComponents();
        MyShopRepository repo = MyShopRepository.getInstance();
        List<Category> cat = repo.getCategories();
        for(Category c : cat){
            cbKategorija.addItem(c);
        }
        List<Manufacturer> man = repo.getManufactureres();
        for(Manufacturer m : man){
            cbProizvodjac.addItem(m);
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    tfNaziv = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    cbKategorija = new javax.swing.JComboBox<>();
    jLabel4 = new javax.swing.JLabel();
    cbProizvodjac = new javax.swing.JComboBox<>();
    jLabel5 = new javax.swing.JLabel();
    tfCena = new javax.swing.JFormattedTextField();
    jLabel6 = new javax.swing.JLabel();
    spKolicina = new javax.swing.JSpinner();
    jButton1 = new javax.swing.JButton();

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("Nov Proizvod");

    jLabel2.setText("Naziv :");

    jLabel3.setText("Kategorija :");

    jLabel4.setText("Proizvodjac :");

    jLabel5.setText("Cena :");

    jLabel6.setText("Kolicina :");

    jButton1.setText("Dodaj");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jLabel2)
                .addComponent(tfNaziv)
                .addComponent(jLabel3)
                .addComponent(cbKategorija, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addComponent(cbProizvodjac, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addComponent(tfCena)
                .addComponent(jLabel6)
                .addComponent(spKolicina, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(tfNaziv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cbKategorija, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cbProizvodjac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel5)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(tfCena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel6)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(spKolicina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 28, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        MyShopRepository repo = MyShopRepository.getInstance();
        repo.addProduct(new Product(0,
                                    tfNaziv.getText(),
                                   ((Category)cbKategorija.getSelectedItem()),
                                    ((Manufacturer)cbProizvodjac.getSelectedItem()),
                                    Double.parseDouble(tfCena.getValue().toString()),
                                    Integer.parseInt(spKolicina.getValue().toString())));
        JOptionPane.showMessageDialog(this, "Snimljeno","Uspesno snimanje",JOptionPane.INFORMATION_MESSAGE);
        MainForm.mainForm.changeContent(new ListProductsPanel());
    } catch (SQLException ex) {
        Logger.getLogger(AddProductPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox<Category> cbKategorija;
    private javax.swing.JComboBox<Manufacturer> cbProizvodjac;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JSpinner spKolicina;
    private javax.swing.JFormattedTextField tfCena;
    private javax.swing.JTextField tfNaziv;
    // End of variables declaration                   
}

The class where i have connected to DB and where are methods i try to use to add data to DB(there are a lot of methods here but i will only add addProduct() method): Connection to DB:

    public class MyShopRepository {
private MyShopRepository() throws SQLException{
   conn = DriverManager.getConnection("jdbc:mysql://localhost/myshop","root","2007991710126");
}
private static MyShopRepository instance;
private final Connection conn;
public static MyShopRepository getInstance() throws SQLException{
    if(instance==null){
        instance = new MyShopRepository();
    }
    return instance;
}

The addProduct() method :

    public void addProduct(Product pr) throws SQLException{
    PreparedStatement ps = conn.prepareStatement("insert into product values (null,?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
    ps.setString(1,pr.name);
    ps.setInt(2,pr.category.id);
    ps.setInt(3, pr.manufacturer.id);
    ps.setDouble(4, pr.price);
    ps.setInt(5, pr.quantity);
    ps.execute();
    if(ps.getUpdateCount()>0){
        ResultSet rs = ps.getGeneratedKeys();
        rs.next();
        pr.id = rs.getInt(1);
    }
}

MySQL that created tables:

    CREATE TABLE `myshop`.`category` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(45) NULL,
    `description` VARCHAR(45) NULL,
    PRIMARY KEY (`id`));

    CREATE TABLE `myshop`.`manufacturer` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(45) NULL,
    `description` VARCHAR(45) NULL,
    PRIMARY KEY (`id`));

    CREATE TABLE `myshop`.`product` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(45) NULL,
    `category` INT NULL,
    `manufacturer` INT NULL,
    `price` DECIMAL(7,2) NULL,
    `quantity` INT NULL,
    PRIMARY KEY (`id`),
    INDEX `fk_pro_cat_idx` (`category` ASC),
    INDEX `fk_pro_man_idx` (`manufacturer` ASC),
    CONSTRAINT `fk_pro_cat`
    FOREIGN KEY (`category`)
    REFERENCES `myshop`.`category` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
    CONSTRAINT `fk_pro_man`
    FOREIGN KEY (`manufacturer`)
    REFERENCES `myshop`.`manufacturer` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

This is the error i get when i click "Dodaj" button(jButton1) in the GUI :

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at myshop.gui.AddProductPanel.jButton1ActionPerformed(AddProductPanel.java:119)
        at myshop.gui.AddProductPanel.access$000(AddProductPanel.java:12)
        at myshop.gui.AddProductPanel$1.actionPerformed(AddProductPanel.java:60)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
        at java.awt.Component.processMouseEvent(Component.java:6535)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
        at java.awt.Component.processEvent(Component.java:6300)
        at java.awt.Container.processEvent(Container.java:2236)
        at java.awt.Component.dispatchEventImpl(Component.java:4891)
        at java.awt.Container.dispatchEventImpl(Container.java:2294)
        at java.awt.Component.dispatchEvent(Component.java:4713)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
        at java.awt.Container.dispatchEventImpl(Container.java:2280)
        at java.awt.Window.dispatchEventImpl(Window.java:2750)
        at java.awt.Component.dispatchEvent(Component.java:4713)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
        at java.awt.EventQueue.access$500(EventQueue.java:97)
        at java.awt.EventQueue$3.run(EventQueue.java:709)
        at java.awt.EventQueue$3.run(EventQueue.java:703)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.awt.EventQueue$4.run(EventQueue.java:731)
        at java.awt.EventQueue$4.run(EventQueue.java:729)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Whats the problem , and how do i get this to work ?

0 Answers0