簡易商品模塊實現

瞭解了數據庫,和java的簡單操做,咱們簡單是實現一個商品窗口;java

三次架構: 持久層:完成內存數據和磁盤數據的轉換;mysql

      業務層:將表現層提供數據處理後,交由持久層完成數據保存sql

      表現層:完成數據的提供和展現,並完成流程控制          數據庫

如下爲實現代碼架構

創建商品類,屬性對應數據庫中商品表格的列ide

package com.project.bean; import java.sql.Date; public class ProductBean { /** 商品編號 */
    private int id; /** 商品名 */
    private String name; /** 商品單價 */
    private int price; /** 商品產地 */
    private String address; /** 商品日期 */
    private Date createDate; public ProductBean() { super(); } public ProductBean(String name, int price, String address, Date createDate) { super(); this.name = name; this.price = price; this.address = address; this.createDate = createDate; } 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 getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Override public String toString() { return "ProductBean [id=" + id + ", name=" + name + ", price=" + price + ", address=" + address + ", createDate=" + createDate + "]\n"; } }

package com.project.dao; import java.sql.Date; import java.util.List; import com.project.bean.ProductBean; /** * 商品持久接口 * * @author Administrator * */
public interface IProductDao { /** * 商品添加 * * @param bean * 商品對象 */
    public void add(ProductBean bean); /** * 按id刪除商品 * * @param id * 商品id */
    public void del(int id); /** * 按id號修改單價 * * @param id * 商品id * @param price * 商品單價 */
    public void update(int id, int price); /** * 按id作查詢 * * @param id * 商品id * @return 商品對象 */
    public ProductBean findById(int id); /** * 動態查詢 * * @param name * 商品名 * @param startDate * 商品起始日期 * @param endDate * 商品結束日期 * @return 商品集合 */
    public List<ProductBean> findByItem(String name, Date startDate, Date endDate); } package com.project.dao.impl; import java.sql.Date; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.project.bean.ProductBean; import com.project.dao.IProductDao; 
package com.project.dao.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /**連接類,爲父類,方便,商品接口實現類,完成數據庫和Java的連接,和數據實現 public class BaseDao { /** 鏈接對象 */
    protected Connection con; /** 預編譯SQL語句執行對象 */
    protected PreparedStatement ps; /** 結果集對象 */
    protected ResultSet rs; /** * 創建鏈接 */
    public void setConnection() { try { Class.forName("org.gjt.mm.mysql.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/admin?characterEncoding=utf-8", "root", "lovo"); } catch (Exception e) { e.printStackTrace(); } } /** * 關閉鏈接 */
    public void closeConnection() { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
 
 

 





/** * 商品持久接口實現類 * * @author Administrator * */ public class ProductDaoImpl extends BaseDao implements IProductDao { public static void main(String[] args) { ProductDaoImpl dao = new ProductDaoImpl(); dao.add(new ProductBean("皮皮蝦", 20, "廣東", Date.valueOf("2017-05-12"))); // dao.del(7); // dao.update(5, 150); // ProductBean bean=dao.findById(1); // System.out.println(bean); // List<ProductBean> list = dao.findByItem("機", Date.valueOf("2016-01-01"), Date.valueOf("2016-12-31")); // System.out.println(list); } @Override public void add(ProductBean bean) { this.setConnection(); try { ps = con.prepareStatement("INSERT INTO t_product(pname,price,createAddress,createDate)VALUES(?,?,?,?)"); ps.setString(1, bean.getName()); ps.setInt(2, bean.getPrice()); ps.setString(3, bean.getAddress()); ps.setDate(4, bean.getCreateDate()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { this.closeConnection(); } } @Override public void del(int id) { this.setConnection(); try { ps = con.prepareStatement("DELETE FROM t_product WHERE id=?"); ps.setInt(1, id); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { this.closeConnection(); } } @Override public void update(int id, int price) { this.setConnection(); try { ps = con.prepareStatement("UPDATE t_product SET price=? WHERE id=?"); ps.setInt(1, price); ps.setInt(2, id); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { this.closeConnection(); } } @Override public ProductBean findById(int id) { ProductBean bean = null; this.setConnection(); try { ps = con.prepareStatement("SELECT*FROM t_product WHERE id=?"); ps.setInt(1, id); rs = ps.executeQuery(); if (rs.next()) { bean = new ProductBean(); bean.setId(rs.getInt("id")); bean.setName(rs.getString("pname")); bean.setPrice(rs.getInt("price")); bean.setAddress(rs.getString("createAddress")); bean.setCreateDate(rs.getDate("createDate")); } } catch (SQLException e) { e.printStackTrace(); } finally { this.closeConnection(); } return bean; } @Override public List<ProductBean> findByItem(String name, Date startDate, Date endDate) { List<ProductBean> list = new ArrayList<ProductBean>(); //拼接字符串,知足sql語句當有名字或者日期是輸出相對應的查找語句 String sql = "SELECT*FROM t_product WHERE 1=1 "; if (name != null && name.length() != 0) { sql += " and pname like '%" + name + "%' "; } if (startDate != null) { sql += " and createDate >='" + startDate + "' "; } if (endDate != null) { sql += " and createDate <='" + endDate + "' "; } this.setConnection(); try { ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { ProductBean bean = new ProductBean(); bean.setId(rs.getInt("id")); bean.setName(rs.getString("pname")); bean.setPrice(rs.getInt("price")); bean.setAddress(rs.getString("createAddress")); bean.setCreateDate(rs.getDate("createDate")); list.add(bean); } } catch (SQLException e) { e.printStackTrace(); } finally { this.closeConnection(); } return list; } }
package com.project.service; import java.sql.Date; import java.util.List; import com.project.bean.ProductBean; /** * 業務持久接口 * @author Administrator * */
public interface IProductService { /** * 添加商品 * @param bean商品對象 */
    public void add(ProductBean bean); /** *刪除商品 * @param id商品id */
    public void del(int id); /** * 按id查詢商品 * @param id商品id * @return 商品對象 */
    public ProductBean findById(int id); /** * 按id修改商品單價 * @param id 商品id * @param price 商品新單價 */
    public void update(int id,int price); /** * 動態條件查詢商品 * @param name 商品名 * @param startDate 起始生產日期 * @param endDate 結束生產日期 * @return 商品集合 */
    public List<ProductBean> findByItem(String name,Date startDate,Date endDate); } package com.project.service.Impl; import java.sql.Date; import java.util.List; import com.project.bean.ProductBean; import com.project.dao.IProductDao; import com.project.dao.impl.ProductDaoImpl; import com.project.service.IProductService; /** * 業務持久接口實現類 * @author Administrator * */
public class ProductSreviceImpl implements IProductService { private  IProductDao dao=new ProductDaoImpl(); @Override public void add(ProductBean bean) { dao.add(bean); } @Override public void del(int id) { dao.del(id); } @Override public ProductBean findById(int id) { return dao.findById(id); } @Override public void update(int id, int price) { dao.update(id, price); } @Override public List<ProductBean> findByItem(String name, Date startDate, Date endDate) { return dao.findByItem(name, startDate, endDate) ; } }
package com.project.frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import java.util.List; import javax.swing.JFrame; import javax.swing.JOptionPane; import com.lovo.netCRM.component.LovoButton; import com.lovo.netCRM.component.LovoTable; import com.lovo.netCRM.component.LovoTxt; import com.project.bean.ProductBean; import com.project.service.IProductService; import com.project.service.Impl.ProductSreviceImpl; import com.project.util.ChangeDate; public class MainFrame extends JFrame { //第一個參數表格加入的容器 //第二個參數表頭列表 //第三個參數表頭對應實體類的屬性名 //第四個參數實體類中主鍵屬性名
    private LovoTable table=new LovoTable(this,new String []{"商品名","商品單價","商品產地","商品日期"} ,new String [] {"name","price","address","createDate"}, "id"); /**商品名文本框*/
    private LovoTxt nameTxt=new LovoTxt("商品名", 400, 50, this); /**起始日期文本框*/
    private LovoTxt startTxt=new LovoTxt("起始日期", 400, 90, this); /**結束日期文本框*/
    private LovoTxt endTxt=new LovoTxt("結束日期", 400, 130, this); /**商品業務組件*/
    private IProductService service=new ProductSreviceImpl(); public MainFrame() { this.setLayout(null); //調用業務方法獲得所有商品
        List<ProductBean> list=service.findByItem("", null, null); table.setSizeAndLocation(50, 30, 300, 200); table.updateLovoTable(list); LovoButton findButton=new LovoButton("查找", 500, 160, this); findButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //獲得文本框數據
                String name=nameTxt.getText(); //在工具類寫判斷日期是否正確方法
                Date startDate=ChangeDate.getDate(startTxt.getText()); Date endDate=ChangeDate.getDate(endTxt.getText()); //調用業務方法獲得查詢結果
                List<ProductBean> list=service.findByItem(name, startDate, endDate); //更新表格數據
 table.updateLovoTable(list); } }); LovoButton addButton=new LovoButton("添加商品", 500, 200, this); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { MainFrame.this.dispose(); new AddFrame(); } }); LovoButton delButton=new LovoButton("刪除", 500, 240, this); delButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //獲得用戶選擇行的id號,若是沒有選擇行,返回-1
                int id=table.getKey(); if(id==-1) { JOptionPane.showMessageDialog(null, "請選擇行"); return; } //調用業務方法刪除
 service.del(id); List<ProductBean> list=service.findByItem("", null, null); table.updateLovoTable(list); } }); LovoButton updateButton=new LovoButton("修改", 500, 280, this); updateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int id=table.getKey(); if(id==-1) { JOptionPane.showMessageDialog(null, "請選擇行"); return; } MainFrame.this.dispose(); new updateFrame(id); } }); this.setSize(700, 400); this.setVisible(true); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(3); } public static void main(String[] args) { MainFrame m=new MainFrame(); } } package com.project.frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import javax.swing.JFrame; import com.lovo.netCRM.component.LovoButton; import com.lovo.netCRM.component.LovoTxt; import com.project.bean.ProductBean; import com.project.service.IProductService; import com.project.service.Impl.ProductSreviceImpl; public class AddFrame extends JFrame { /** 商品名文本框 */
    private LovoTxt nameTxt = new LovoTxt("商品名", 50, 50, this); /** 商品價格 文本框 */
    private LovoTxt priceTxt = new LovoTxt("商品價格", 50, 100, this); /** 商品產地文本框 */
    private LovoTxt addressTxt = new LovoTxt("商品產地", 50, 150, this); /** 生產日期文本框 */
    private LovoTxt dateTxt = new LovoTxt("生產日期", 50, 200, this); private IProductService service=new ProductSreviceImpl(); public AddFrame() { this.setLayout(null); LovoButton addButton = new LovoButton("添加", 100, 250, this); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if(check()==false) { return; } //界面數據封裝成實體對象
                ProductBean bean=new ProductBean(); System.out.println(nameTxt.getText()); bean.setName(nameTxt.getText()); bean.setPrice(Integer.parseInt(priceTxt.getText())); bean.setAddress(addressTxt.getText()); bean.setCreateDate(Date.valueOf(dateTxt.getText())); //調用業務方法完成添加
 service.add(bean); //卸載窗體
                AddFrame.this.dispose(); //產生新窗體
                new MainFrame(); } }); this.setSize(300, 400); this.setVisible(true); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(3); } private boolean check() { String info=""; if(nameTxt.getText().matches("[\\w\\u4e00-\\u9fa5]{2,}")==false) { info+="商品爲兩個以上的字母、數字、漢子\n"; } if(priceTxt.getText().matches("\\d+")==false) { info+="單價必須爲數字\n"; } if(addressTxt.getText().matches("[\\w\\u4e00-\\u9fa5]{2,}")==false) { info+="產地必須爲兩個以上的漢子\n"; } if(dateTxt.getText().matches("\\d{4}-\\d{2}-\\d{2}")==false) { info+="日期格式XXXX-XX-XX"; } if(info.length()!=0) { return false; } return true; } } package com.project.frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import com.lovo.netCRM.component.LovoButton; import com.lovo.netCRM.component.LovoLabel; import com.lovo.netCRM.component.LovoTxt; import com.project.bean.ProductBean; import com.project.service.IProductService; import com.project.service.Impl.ProductSreviceImpl; public class updateFrame extends JFrame { private LovoLabel nameLabel = new LovoLabel("商品名", 50, 20, this); private LovoTxt priceTxt = new LovoTxt("商品單價", 50, 70, this); private LovoLabel addressLabel = new LovoLabel("商品產地", 50, 120, this); private LovoLabel dateLabel = new LovoLabel("生產日期", 50, 170, this); private IProductService service = new ProductSreviceImpl(); /** 須要修改商品的id */
    private int productId; public updateFrame(int id) { this.productId = id; this.setLayout(null); this.init(); LovoButton updataButton = new LovoButton("修改", 100, 220, this); updataButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { service.update(productId, Integer.parseInt(priceTxt.getText())); updateFrame.this.dispose(); new MainFrame(); } }); this.setSize(400, 300); this.setVisible(true); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(3); } /** * 初始化 */
    public void init() { // 按id獲得須要修改的商品對象,將商品對象的屬性值填充文本
        ProductBean bean = service.findById(productId); nameLabel.setText(bean.getName()); priceTxt.setText(bean.getPrice() + ""); addressLabel.setText(bean.getAddress()); dateLabel.setText(bean.getCreateDate().toString()); } }

以上爲代碼實現,不少都是以前學過的而且應該掌握的知識,只要理解參透這些學過的知識,在寫的時候思路清晰且明確,那麼代碼實現是很簡單的,注意每一個流程實現的細節。工具

以及注意三層架構數據傳遞的方式。this

相關文章
相關標籤/搜索