JDBC技术【分页查询、数据库连接池、应用程序分层、封装通用的BaseDao】(四)-全面详解(学习总结---从入门到深化)(中):https://developer.aliyun.com/article/1419275
BaseDaoImpl接口实现类
/** * 通用接口实现类 */ public class BaseDaoImpl implements BaseDao { /** * 通用的DML操作方法 */ @Override public int executeUpdate(String sql, Object[] param) { Connection conn = null; PreparedStatement ps = null; int row; try{ conn = JdbcDruidUtil.getConnection(); ps = conn.prepareStatement(sql); //得到参数的个数 ParameterMetaData pd = ps.getParameterMetaData(); for(int i =0;i<pd.getParameterCount();i++){ ps.setObject(i+1,param[i]); } row = ps.executeUpdate(); }catch (Exception e){ e.printStackTrace(); //通过自定义异常解决异常耦合问题 throw new ApplicationException(e.getMessage()); }finally{ JdbcDruidUtil.closeResource(ps,conn); } return row; } /** * 通用查询方法 */ @Override public <T> List<T> select(String sql, Object[] param, Class<T> clazz) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; List<T> list = new ArrayList<>(); try{ conn = JdbcDruidUtil.getConnection(); ps = conn.prepareStatement(sql); //得到参数的个数 ParameterMetaData pd = ps.getParameterMetaData(); for(int i =0;i<pd.getParameterCount();i++){ ps.setObject(i+1,param[i]); } rs = ps.executeQuery(); //获取结果集信息 ResultSetMetaData rm = rs.getMetaData(); while(rs.next()){ //OMR映射 //通过反射实例化实体类对象 T bean = clazz.newInstance(); //实体类的属性名必须要和表的列名相同。 for(int i=0;i<rm.getColumnCount();i++){ //得到列名 String columnName = rm.getColumnName(i+1); //获取列的值 Object value = rs.getObject(columnName); //通过BeanUtil工具类讲值映射到对象中 BeanUtils.setProperty(bean,columnName,value); } list.add(bean); } }catch (Exception e){ e.printStackTrace(); //通过自定义异常解决异常耦合问题 throw new ApplicationException(e.getMessage()); }finally{ JdbcDruidUtil.closeResource(rs,ps,conn); } return list; } }
UsersDao接口
public interface UsersDao extends BaseDao { /** * 根据用户ID查询用户 * */ Users selectUsersById(int userid); /** * 修改用户信息 */ int updateUsersById(Users users); /** * 根据用户姓名模糊查询 */ List<Users> selectUsersByLikeName(String username); }
UsersDaoImpl接口实现类
public class UsersDaoImpl extends BaseDaoImpl implements UsersDao { /** * 根据用户ID查询用户 * @param userid * @return */ @Override public Users selectUsersById(int userid){ Connection conn =null; PreparedStatement ps = null; ResultSet rs = null; Users users = null; try{ conn = JdbcDruidUtil.getConnection(); ps = conn.prepareStatement("select * from users where userid = ?"); ps.setInt(1,userid); rs = ps.executeQuery(); while(rs.next()){ //手动orm映射 users = new Users(); users.setUserid(rs.getInt("userid")); users.setUsername(rs.getString("username")); users.setUserage(rs.getInt("userage")); } }catch(Exception e){ e.printStackTrace(); //通过自定义异常解决异常耦合问题 throw new ApplicationException(e.getMessage()); }finally{ JdbcDruidUtil.closeResource(rs,ps,conn); } return users; } /** * 修改用户信息 */ @Override public int updateUsersById(Users users){ String sql = "update users set userage = ? where userid = ? "; Object[] param = new Object[] {users.getUserage(),users.getUserid()}; return this.executeUpdate(sql,param); } @Override public List<Users> selectUsersByLikeName(String username) { String sql = "select * from users where username like ?"; Object[] param = new Object[] {"%"+username+"%"}; return this.select(sql,param,Users.class); } }
对象的关联关系
关联关系简介
关联关系(Association),是一种拥有的关系,它使一个对象知道另 一个对象的属性和方法。关联可以是双向的,也可以是单向的。在 Java语言中,关联关系一般使用成员变量来实现。
对象的关联关系解决了什么问题
在多表查询时,使用对象关联关系能够更合理的存放查询到的结果集数据。
关联关系的方向性
单向 只在一侧关联了对方。
双向 两侧相互关联了对方。
创建对象的关联关系
创建表
orders表
CREATE TABLE `orders` ( `orderid` int(11) NOT NULL AUTO_INCREMENT, `orderprice` float(11,2) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, PRIMARY KEY (`orderid`), KEY `orders_fk` (`user_id`), CONSTRAINT `orders_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`userid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
items表
CREATE TABLE `items` ( `itemid` int(11) NOT NULL, `itemname` varchar(30) DEFAULT NULL, `itemprice` float(11,2) DEFAULT NULL, `itemnum` int(11) DEFAULT NULL, PRIMARY KEY (`itemid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
orders_itmes表
CREATE TABLE `orders_items` ( `order_id` int(11) NOT NULL, `item_id` int(11) NOT NULL, PRIMARY KEY (`order_id`,`item_id`), KEY `orders_items_fk2` (`item_id`), CONSTRAINT `orders_items_fk` FOREIGN KEY (`order_id`) REFERENCES `orders` (`orderid`), CONSTRAINT `orders_items_fk2` FOREIGN KEY (`item_id`) REFERENCES `items` (`itemid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
对象的关联关系
Users对象
public class Users { private int userid; private String username; private int userage; //创建与Orders的关联关系 private List<Orders> orders = new ArrayList<>(); public List<Orders> getOrders() { return orders; } public void setOrders(List<Orders> orders) { this.orders = orders; } @Override public String toString() { return "Users{" + "userid=" + userid + ", username='" + username +'\'' + ", userage=" + userage + '}'; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserage() { return userage; } public void setUserage(int userage) { this.userage = userage; } }
Orders对象
public class Orders { private int orderid; private double orderprice; //关联Users private Users users; //关联Items private List<Items> items =new ArrayList<>(); public int getOrderid() { return orderid; } public void setOrderid(int orderid) { this.orderid = orderid; } public double getOrderprice() { return orderprice; } public void setOrderprice(double orderprice) { this.orderprice = orderprice; } public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } public List<Items> getItems() { return items; } public void setItems(List<Items> items) { this.items = items; } }
Items对象
public class Items { private int itemid; private String itemname; private double itemprice; private int itemnum; //关联Orders private List<Orders> orders = new ArrayList<>(); public int getItemid() { return itemid; } public void setItemid(int itemid) { this.itemid = itemid; } public String getItemname() { return itemname; } public void setItemname(String itemname) { this.itemname = itemname; } public double getItemprice() { return itemprice; } public void setItemprice(double itemprice) { this.itemprice = itemprice; } public int getItemnum() { return itemnum; } public void setItemnum(int itemnum) { this.itemnum = itemnum; } public List<Orders> getOrders() { return orders; } public void setOrders(List<Orders> orders) { this.orders = orders; } }
使用对象关联关系存放查询数据
需求:查询用户ID为1的用户信息他的订单信息,以及订单中所包含 的商品信息。
SQL语句
select * from users u,orders o, orders_items oi, items i WHERE u.userid = o.user_id and o.orderid = oi.order_id and oi.item_id = i.itemid and u.userid =1
UserDao接口
/** * 查询用户ID为1的用户信息他的订单信息, * 以及订单中所包含的商品信息。 */ Users selectUsers(int userid);
UsersDaoImpl接口实现类
/** * 查询用户ID为1的用户信息他的订单信息, * 以及订单中所包含的商品信息。 */ @Override public Users selectUsers(int userid) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Users users =new Users(); try{ conn = JdbcDruidUtil.getConnection(); ps = conn.prepareStatement("select * from users u,orders o, orders_items oi, items i WHERE\n" + "u.userid = o.user_id and o.orderid = oi.order_id and oi.item_id = i.itemid \n" + "and u.userid =?"); ps.setInt(1,userid); rs = ps.executeQuery(); while(rs.next()){ //Users对象的ORM映射 users.setUserid(rs.getInt("userid")); users.setUsername(rs.getString("username")); users.setUserage(rs.getInt("userage")); //Orders对象的ORM映射 Orders orders = new Orders(); orders.setOrderid(rs.getInt("orderid")); orders.setOrderprice(rs.getDouble("orderprice")); users.getOrders().add(orders); //Items对象的ORM映射 Items items = new Items(); items.setItemid(rs.getInt("itemid")); items.setItemname(rs.getString("itemname")); items.setItemprice(rs.getDouble("itemprice")); items.setItemnum(rs.getInt("itemnum")); orders.getItems().add(items); } }catch (Exception e){ e.printStackTrace(); //通过自定义异常解决异常耦合问题 throw new ApplicationException(e.getMessage()); }finally{ JdbcDruidUtil.closeResource(rs,ps,conn); } return users; }
UsersService接口
Users findUsers(int userid);
UsersService接口实现类
@Override public Users findUsers(int userid) { UsersDao ud = new UsersDaoImpl(); return ud.selectUsers(userid); }