java - 这个类设计错了吗?

标签 java mysql class

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

我有一个大问题。我想不出应该在哪里放置保存数据的方法。我应该为数据库操作创建一个新类,还是应该将它们放在库存类中。

谢谢!!

我的类(class)是:

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

最佳答案

快速回答是的,这是一个糟糕的设计抱歉,这是我会做的改进:

  • 尝试在类之间实现松散耦合,每个类都应该实现一个接口(interface)。例如。

    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 会有这样的引用(这可以被注入(inject)):

    ConnectionManager connectionManager = new MysqlConnectionManager();
  • 尝试遵循 Camel 案例实践 ( Wiki source )

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

    private String barCode;
    
    public String getBarCode(){
        return this.barCode;
    }
    
    public void setBarCode(final String barCode){
        this.barCode = barCode;
    }
    
  • 遵循 DAO 模式 ( Wiki source ),基本上您需要创建一个类名 ItemDao 来处理“项目”的所有数据库操作。

  • Inventory 应该重命名为 ItemService,它不应该只有 DAO 才能访问 DB,因此如果您需要实现另一个 DAO,很容易替换它。

  • 不要过多地使用 System.out.print,而是将您的类配置为使用输出流,以便使用文件或字符串输出流轻松配置它。

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

关于java - 这个类设计错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35682474/

相关文章:

java - 仅适用于 LaF Nimbus 的空指针异常

java - 使用 Java 从 Json Payload 获取字段 ID 值

c# - 静态类与具有构造函数性能的类

c++ - 想要销毁我制作的堆栈

java - 如何创建虚拟 Oracle 服务器来与 Toad 连接

java - 如何在 Horizo​​ntalBarChart 中显示条形标签?

mysql - 选择计数(*)在 MySql 表上花费很长时间

php - MYSQL Join Query Multiple Tables 部分字段显示重复结果

MySQL 错误 1064 单列表

java - 在两个类之间传递变量