了解了数据库,和java的简单操作,我们简单是实现一个商品窗口;
三次架构: 持久层:完成内存数据和磁盘数据的转换;
业务层:将表现层提供数据处理后,交由持久层完成数据保存
表现层:完成数据的提供和展示,并完成流程控制
以下为实现代码
建立商品类,属性对应数据库中商品表格的列
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 + "]
";
}
}
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+="商品为两个以上的字母、数字、汉子
";
}
if(priceTxt.getText().matches("\d+")==false)
{
info+="单价必须为数字
";
}
if(addressTxt.getText().matches("[\w\u4e00-\u9fa5]{2,}")==false)
{
info+="产地必须为两个以上的汉子
";
}
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());
}
}
以上为代码实现,很多都是之前学过的并且应该掌握的知识,只要理解参透这些学过的知识,在写的时候思路清晰且明确,那么代码实现是很简单的,注意每个流程实现的细节。
以及注意三层架构数据传递的方式。