这个班级设计错了吗?

时间:2016-02-28 12:22:57

标签: java mysql class

我是一名java开发人员。我正在用java和mysql开发一个股票应用程序。

我有一个很大的问题。我无法弄清楚应该在哪里放置方法来保存数据。我应该为DB operatios创建一个新类,还是应该将它们放在库存类中。

谢谢!

我的课程是:

package inventory;

public class Item
{
private String bc; // ITEM BARCODE
private String description; // ITEM DESCRIPTION
private int nItm; // NUMBER OF ITEMS IN A PACK OR ITEMS

/**
 * Constructor for objects of class item
 *  - Initialise instance variables bc, description to null and nItm to 0
 */
public Item()
{
    // initialise instance variables
    bc = null;
    description = null;
    nItm = 0;
}

/**
 * Constructor for objects of class item
 *  - Initialise instance variables to a given parameters.
 *  @param bc           String item codebar.
 *  @param description  String description of the item.
 *  @param nItm         int items or number of items in a pack
 */
public Item(String bc,String description,int nItm)
{
    this.bc = bc;
    this.description = description;
    this.nItm = nItm;
}

/**
 * Gets a codebar from the item
 *
 * @return     A String with the codebar item.
 */
public String getBarcode()
{
    // put your code here
    return bc;
}

/**
 * Gets description from the item
 * 
 * @return     A String with the description item.
 */
public String getDescription()
{
    return description;
}

/**
 * Gets the number of items in stock
 * 
 * @return     Number of items in stock.
 */
public int getNumberOfItems()
{
    return nItm;
}

/**
 * Set the value for codebar
 * 
 * @param  bc  Barcode item. 
 */
public void setBarcode(String bc)
{
    this.bc = bc;
}

/**
 * Set the value for description
 * 
 * @param  description   Description item.
 */
public void setDescription(String description)
{
    this.description = description;
}

/**
 * Set the value for nItm
 * 
 * @param  nItm   Number of items or items in a pack
 */
public void setNumberOfItems(int nItm)
{
    this.nItm = nItm;
}
/**
 * Shows an item with this template "| %-16s | %-44s | %5d |" 
 */
public void showItem()
{
    System.out.print("\f");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| BARCODE          | DESCRIPTION                                  | STOCK |\n");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| %-16s | %-44s | %5d |",this.bc,this.description,this.nItm);
    System.out.printf("+-------------------------------------------------------------------------+\n");
}

}

package inventory;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import DataBases.*;
import java.util.Scanner;
import java.sql.*;
public class Inventory
{
// instance variables - replace the example below with your own
private Item[] inventory; // array of items
public int nreg; // NUMBER OF ITEMS STORED

/**
 * Constructor for objects of class Inventory
 */
public Inventory() throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    // initialise instance variables

    this.inventory = new Item[100];
    loadData();
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void addItem(String bc,String description,int nItm)
{
    // put your code here
    Item item;
    item = new Item(bc,description,nItm);
    inventory[nreg] = item;
    nreg++;
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void loadData() throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    Mysql c = new Mysql();
    ResultSet rs;

    c.On();
    rs = c.ExeGet("SELECT * FROM item");
    while(rs.next())
    {
        inventory[nreg] = new Item(rs.getString("barcode"),rs.getString("description"),rs.getInt("nItems"));
        this.nreg++;
    }
    c.Off();
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void searchItem()
{
    System.out.print("\f");
    int op;
    System.out.printf("\tSEARCH MENU\n");
    System.out.printf("\t===========\n\n");
    System.out.printf("\t1.BY BARCODE.\n");
    System.out.printf("\t2.BY ITEM.\n");
    System.out.printf("\t3.BY NUMBER OF ITEMS.\n");
    System.out.printf("\t0.EXIT.\n\n");
    System.out.printf("\tOPTION: ");

    Scanner reader = new Scanner(System.in);
    op = reader.nextInt();
    switch(op)
    {
        case 0: break;
        //case 1: searchByBarcode();break;
        //case 2: searchByItem();break;
        case 3: searchByNumberOfItems();break;
        default: break;
    }
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
/*
private void searchByBarcode()
{
    int op;
    int flag = 0;
    Item reg = new Item();

    do{
        System.out.print("\f");
        System.out.println("OPTION 1. OK");
        System.out.printf("BARCODE: ");
        String bc;
        Scanner reader = new Scanner(System.in);
        bc = reader.nextSt();
    //  AQUI VA UN TRY COMO UNA CASA
        for(int i=0;i<nreg;i++)
        {
            if (inventory[i].getBarcode() == bc)
            {
                reg = inventory[i];
                flag = 1;
                break;
            }
        }
        if (flag == 1)
        {
            reg.showItem();
        }
        else
        {
            System.out.printf("I CAN NOT FIND %d",bc);
        }
        System.out.println("CONTINUE SEARCHING (0/1): ");
        op = reader.nextInt();

    }while(op != 1);
}
*/

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
private void searchByNumberOfItems()
{
    System.out.print("\f");
    System.out.println("OPTION 3. OK");
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void addNewItem(String barcode,String description,int nItm) throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    Mysql c = new Mysql();
    Item i = new Item(barcode,description,nItm);
    String q = "INSERT INTO inventory.item (barcode,description,nItems) VALUES ('" + i.getBarcode() + "','" 
                + i.getDescription() + "'," + i.getNumberOfItems() + ");";

    c.On();
    c.Exe(q);
    c.Off();
    nreg++;
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void listItems() throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    Mysql c = new Mysql();
    ResultSet rs;

    c.On();
    rs = c.ExeGet("SELECT * FROM item");
    System.out.print("\f");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| BARCODE          | DESCRIPTION                                  | STOCK |\n");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    while(rs.next())
    {
        //System.out.println("" + rs.getString("barcode") + "     " + rs.getString("description") + "     " + rs.getInt("nItems"));

        System.out.printf("| %-16s | %-44s | %5d |\n",rs.getString("barcode"),rs.getString("description"),rs.getInt("nItems"));
    }
    System.out.printf("+-------------------------------------------------------------------------+\n");
    c.Off();
}

public void listArray()
{
    System.out.print("\f");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| BARCODE          | DESCRIPTION                                  | STOCK |\n");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    for(int i = 0;i<nreg;i++)
    {
        System.out.printf("| %-16s | %-44s | %5d |\n",inventory[i].getBarcode(),inventory[i].getDescription(),inventory[i].getNumberOfItems());
    }
    System.out.printf("+-------------------------------------------------------------------------+\n");
    System.out.printf("| NUMBER OF ITEMS: %3d                                                    |\n",nreg);
    System.out.printf("+-------------------------------------------------------------------------+\n");
}

}

package DataBases;
import java.sql.*;


public class Mysql
{
// instance variables - replace the example below with your own
private String host;
private String user;
private String pass;
private String db;
private int port;
private Connection connection;

/**
 * Constructor for objects of class Mysql
 */
public Mysql()throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
    // initialise instance variables
    this.host = "localhost";
    this.user = "inventory";
    this.pass = "123456";
    this.port = 3306;
    this.db = "inventory";
    this.Init();
}

public Mysql(String host,String user,String pass,int port,String db) throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
    this.host = host;
    this.user = user;
    this.pass = pass;
    this.port = port;
    this.db = db;
    this.Init();
}


public void Init() throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
    // put your code here
    Class.forName("com.mysql.jdbc.Driver").newInstance();
}

public void On() throws SQLException
{

    this.connection = DriverManager.getConnection("jdbc:mysql://"+ this.host +"/" + this.db,this.user,this.pass);
}

public void Off() throws SQLException
{

    this.connection.close();
}

public ResultSet ExeGet(String Query) throws SQLException
{
    Statement st = this.connection.createStatement();
    return (ResultSet) st.executeQuery(Query);
}

public int Exe(String Query) throws SQLException
{

    Statement st = this.connection.createStatement();
    return st.executeUpdate(Query);
}

}

1 个答案:

答案 0 :(得分:0)

快速回答是的,这是一个糟糕的设计对不起,我会采取以下措施来改善它:

  • 尝试实现类之间的松散耦合,每个类应该是一个接口的实现。例如。

    public interface ConnectionManager {
      void On() throws SQLException;
      void Off() throws SQLException;
      ResultSet ExeGet(String Query) throws SQLException;
      int Exe(String Query) throws SQLException;
    }
    
    public class MysqlConnectionManager implements ConnectionManager {
      @Override
      public void On() throws SQLException {
      }
      @Override
      public void Off() throws SQLException {
      }
      @Override
      public ResultSet ExeGet(String Query) throws SQLException {
      }
      @Override
      public int Exe(String Query) throws SQLException {
      }
    }
    

然后你的DAO会有这样的引用(可以注入):

    ConnectionManager connectionManager = new MysqlConnectionManager();
  • 尝试按照骆驼案例练习(Wiki source

  • 您的属性和关联方法应根据您的属性名称共享相同的名称。

    private String barCode;
    
    public String getBarCode(){
        return this.barCode;
    }
    
    public void setBarCode(final String barCode){
        this.barCode = barCode;
    }
    
  • 遵循DAO模式(Wiki source),基本上您需要创建一个类名ItemDao,它将使用DB来处理所有操作&#39;项目&#39;。

  • 应该将库存重命名为ItemService,并且它不应该只访问数据库DAO,因此如果您需要实现另一个DAO,则很容易替换它。

    < / LI>
  • 过多地使用System.out.print,而是将您的类配置为使用输出流,因此可以使用文件或字符串输出流轻松配置。

  • 要将数据注入数据库,请使用预准备语句而不是在查询中连接数据(SQL injection