samedi 28 novembre 2015

JAVA MVC accessing database

I'm studying java and MVC.
Now I'm trying to connect my software with database sqlite.

I have my Model:

package model;

public class Station {
    private String cnpj;
    private String cep;
    private String razao_social;

    //Constructor
    public Station(){

    }

    public Station(String cnpj, String cep, String razaoSocial){
        this.cnpj = cnpj;
        this.cep = cep;
        this.razao_social = razaoSocial;               
    }    

    //Gets Setters

    public String getCnpj() {
        return cnpj;
    }

    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public String getRazao_social() {
        return razao_social;
    }

    public void setRazao_social(String razao_social) {
        this.razao_social = razao_social;
    }
}  

I have my TableModel:

package model;

import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

public class TableModelStation extends AbstractTableModel{
    private static final String[] columnNames = {"cnpj", "razao_social", "nome_fantasia", "bandeira", "endereco", "bairro", "cep", "imagem"};

    private ArrayList<Station> stations;

    public TableModelStation(){
        stations = new ArrayList<>();
    }

    public void addStation(Station station){
        this.stations.add(station);
        fireTableDataChanged();
    }

    public void removeStation(int rowIndex){
        this.stations.remove(rowIndex);
        fireTableDataChanged();
    }   

    @Override
    public String getColumnName(int columnIndex){
        return columnNames[columnIndex]; 
    }

    @Override
    public int getRowCount() {
       return this.stations.size();
    }

    @Override
    public int getColumnCount() {
       return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex){
            case 0: 
                return this.stations.get(rowIndex).getCnpj();

            case 1:
                return this.stations.get(rowIndex).getRazao_social();
        }
        return null;
    }
}

I want to create the connection to database and also write the sql codes for my model (crud) . So:

1) Should I create another package to separate the connection ? Maybe an Interface ?
2) Should I create something like StationDAO to implement my model CRUD ?

What is the right way to do it ? Following the MVC Rules... I'm really lost.


Aucun commentaire:

Enregistrer un commentaire