使用泛型实现工具类功能
Posted 郭慕荣博客园
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用泛型实现工具类功能相关的知识,希望对你有一定的参考价值。
使用泛型实现公用代码调用,只要是满足条件的入参,出参都是可以实现调用的。代码如下所示:
@Data public class CommonParams private Long id; private String name;
@Data public class BaseDto private Long id;
public class FanXing public <T extends BaseDto, R extends CommonParams> void convert(T t, List<R> r) R result = r.stream().filter(data -> data.getId().equals(t.getId())).findFirst().orElse(null); // 实现逻辑。。。。。 public <T extends CommonParams,R extends CommonResult> R convert(T t) // 实现逻辑 R result = null; result.setCode(result.getCode()); return result;
总结:使用泛型,可以让满足条件的入参,出参可以调用公共逻辑,实现代码的封装。
郭慕荣博客园
jdbc增删改查操作,封装工具类,实现泛型接口无限套娃
jdbc基本操作:
(1)加载并注册数据库驱动。
(2)通过DriverManager获取数据库连接。
(3)通过Connection对象获取Statement对象。
(4)使用Statement执行SQL语句。
(5)操作ResultSet结果集。
(6)关闭连接,释放资源。
数据库的操作其实都差不多,我们可以把相同的内容写成方法、工具类,这样可以极大地减小耦合度,也方便我们以后的套用,可以无限套娃。
这里用的是mysql数据库
下面看看具体操作
第一步先建数据表吧
good商品表
CREATE TABLE `good` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '商品id',
`name` varchar(20) NOT NULL COMMENT '商品名称',
`price` float NOT NULL COMMENT '商品价格',
`stock` int(10) DEFAULT NULL COMMENT '商品库存',
`count` int(10) unsigned zerofill DEFAULT '0000000000' COMMENT '订单量',
`imgUrl` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '商品图片',
`type` varchar(20) DEFAULT NULL COMMENT '商品类型',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=111121 DEFAULT CHARSET=utf8
user用户表
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`name` varchar(20) NOT NULL COMMENT '用户名',
`password` varchar(16) NOT NULL COMMENT '密码',
`mobile` int(13) DEFAULT NULL COMMENT '电话号码',
`qq` int(12) DEFAULT NULL COMMENT 'QQ号码',
`signinTime` datetime DEFAULT NULL COMMENT '注册时间',
`count` int(10) DEFAULT NULL COMMENT '购买次数',
`address` varchar(255) DEFAULT NULL COMMENT '用户地址',
`role` varchar(10) DEFAULT NULL COMMENT '用户角色',
`email` varchar(255) DEFAULT NULL COMMENT '用户邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11113 DEFAULT CHARSET=utf8
底层都是一样的,可以写个工具类
.
DBUtil.java工具类
package com.xmj.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil
private final static String DRIVER = "com.mysql.cj.jdbc.Driver";
private final static String URL ="jdbc:mysql://127.0.0.1:3306/你的数据库名?useSSL=false&serverTimezone=UTC";
private final static String USERNAME = "用户名";
private final static String PASSWORD = "密码";
public static Connection connection = null;
public static PreparedStatement pstmt = null;
public static ResultSet rs = null;
public static Connection getConnection() throws ClassNotFoundException, SQLException
Class.forName(DRIVER);
return DriverManager.getConnection(URL,USERNAME,PASSWORD);
public static PreparedStatement createPreparedStatement(String sql,Object[] params) throws SQLException, ClassNotFoundException
pstmt = getConnection().prepareStatement(sql);
if(params!=null)
for(int i=0;i<params.length;i++)
pstmt.setObject(i+1, params[i]);
return pstmt;
//查询总数
public static int getTotalCount(String sql)
int count = -1;
try
pstmt = createPreparedStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
if(rs.next())
count = rs.getInt(1);
catch (ClassCastException e)
// TODO: handle exception
e.printStackTrace();
catch (SQLException e)
// TODO: handle exception
e.printStackTrace();
catch (Exception e)
// TODO: handle exception
e.printStackTrace();
finally
closeAll(rs, pstmt, connection);
return count;
//增删改
public static boolean excuteUpdate(String sql,Object[] params) throws ClassNotFoundException
try
pstmt = createPreparedStatement(sql,params);
int count = pstmt.executeUpdate();
if(count>0) return true;
else return false;
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
return false;
catch (Exception e)
// TODO: handle exception
e.printStackTrace();
return false;
finally
closeAll(null,pstmt,connection);
//查
public static ResultSet executeQuery(String sql,Object[] params)
try
pstmt = createPreparedStatement(sql,params);
rs = pstmt.executeQuery();
return rs;
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
return null;
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
return null;
catch (Exception e)
// TODO: handle exception
e.printStackTrace();
return null;
finally
closeAll(null,null,connection);
public static void closeAll(ResultSet rs ,Statement stmt,Connection connection)
try
if(rs!=null)rs.close();
// if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
Good实体类
package com.xmj.entity;
public class Good
private Integer id;
private String name;
private Float price;
private Integer stock;
private Integer count;
private String imgUrl;
private String type;
/**
* @return the id
*/
public Integer getId()
return id;
public Good(String name, Float price, Integer stock, Integer count, String imgUrl, String type)
super();
this.name = name;
this.price = price;
this.stock = stock;
this.count = count;
this.imgUrl = imgUrl;
this.type = type;
/**
* @param id the id to set
*/
public void setId(Integer id)
this.id = id;
/**
* @return the name
*/
public String getName()
return name;
/**
* @param name the name to set
*/
public void setName(String name)
this.name = name;
/**
* @return the price
*/
public Float getPrice()
return price;
/**
* @param price the price to set
*/
public void setPrice(Float price)
this.price = price;
/**
* @return the stock
*/
public Integer getStock()
return stock;
/**
* @param stock the stock to set
*/
public void setStock(Integer stock)
this.stock = stock;
/**
* @return the count
*/
public Integer getCount()
return count;
/**
* @param count the count to set
*/
public void setCount(Integer count)
this.count = count;
/**
* @return the imgUrl
*/
public String getImgUrl()
return imgUrl;
/**
* @param imgUrl the imgUrl to set
*/
public void setImgUrl(String imgUrl)
this.imgUrl = imgUrl;
/**
* @return the type
*/
public String getType()
return type;
/**
* @param type the type to set
*/
public void setType(String type)
this.type = type;
public Good(Integer id, String name, Float price, Integer stock, Integer count, String imgUrl, String type)
super();
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.count = count;
this.imgUrl = imgUrl;
this.type = type;
public Good()
super();
user实体类
package com.xmj.entity;
import java.util.Date;
public class User
private Integer id;
private String name;
private String password;
private Integer mobile;
private String role;
private Integer QQ;
private String email;
private Date signinTime;
private Integer count;
private String address;
/**
* @return the id
*/
public Integer getId()
return id;
/**
* @param id the id to set
*/
public void setId(Integer id)
this.id = id;
/**
* @return the name
*/
public String getName()
return name;
/**
* @param name the name to set
*/
public void setName(String name)
this.name = name;
/**
* @return the password
*/
public String getPassword()
return password;
/**
* @param password the password to set
*/
public void setPassword(String password)
this.password = password;
/**
* @return the mobile
*/
public Integer getMobile()
return mobile;
/**
* @param mobile the mobile to set
*/
public void setMobile(Integer mobile)
this.mobile = mobile;
/**
* @return the role
*/
public String getRole()
return role;
/**
* @param role the role to set
*/
public void setRole(String role)
this.role = role;
/**
* @return the qQ
*/
public Integer getQQ()
return QQ;
/**
* @param qQ the qQ to set
*/
public void setQQ(Integer qQ)
QQ = qQ;
/**
* @return the email
*/
public String getEmail()
return email;
/**
* @param email the email to set
*/
public void setEmail(String email)
this.email = email;
/**
* @return the signinTime
*/
public Date getSigninTime()
return signinTime;
/**
* @param signinTime the signinTime to set
*/
public void setSigninTime(Date signinTime)
this.signinTime = signinTime;
/**
* @return the count
*/
public Integer getCount()
return count;
/**
* @param count the count to set
*/
public void setCount(Integer count)
this.count = count;
/**
* @return the address
*/
public String getAddress()
return address;
/**
* @param address the address to set
*/
public void setAddress(String address)
this.address = address;
public User(Integer id, String name, String password, Integer mobile, String role, Integer qQ, String email,
Date signinTime, Integer count, String address)
super();
this.id = id;
this.name = name;
this.password = password;
this.mobile = mobile;
this.role = role;
QQ = qQ;
this.email = email;
this.signinTime = signinTime;
this.count = count;
this.address = address;
public User(String name, String password, Integer mobile, String role, Integer qQ, String email,
Date signinTime, Integer count, String address)
super();
this.name = name;
this.password = password;
this.mobile = mobile;
this.role = role;
QQ = qQ;
this.email = email;
this.signinTime = signinTime;
this.count = count;
this.address = address;
泛型的好处就是,我们不用定义类型,让你的代码更通用。比如我们需要返回类型是一个User类和Good类,不使用泛型就需要写两个方法,如果使用泛型,就只需要用T来泛指未知类,在我们调用的时候,直接用我们需要的类就可以了。
IMapper.java泛型接口
package com.xmj.mapper;
import java.sql.ResultSet;
import java.util.List;
import com.xmj.entity.DataVO;
import com.xmj.entity.Good;
import com.xmj.entity.Order;
import com.xmj.entity.User;
public interface IMapper<T>
//查总数
public int getTotalCount();
//判断是否存在
public boolean isExist(int id) ;
//增
public boolean add(T t);
//改
public boolean updateById(int id, T good) throws ClassNotFoundException;
//删
public boolean deleteById(int sno) ;
//查全部
public List<T> queryAll();
//查,限制页数
public List<T> queryByPage(int currentPage, int pageSize);
//根据id查
public T queryById(int id);
GoodMapper进行持久化操作,实现IMapper接口,然后实现接口的方法
GoodMapper持久化层
package com.xmj.mapper;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xmj.entity.DataVO;
import com.xmj.entity.Good;
import com.xmj.entity.Order;
import com.xmj.util.DBUtil;
public class GoodMapper implements IMapper<Good>
@Override
public int getTotalCount()
String sql = "select count(*) from good;";
return DBUtil.getTotalCount(sql);
@Override
public boolean isExist(int id)
return queryById(id)!=null?true:false;
@Override
public boolean add(Good good)
String sql = "insert into good(name,price,stock,count,imgUrl,type)values(?,?,?,?,?,?)";
Object[] params = good.getName(),good.getPrice(),good.getStock(),good.getCount(),good.getImgUrl(),good.getType();
try
return DBUtil.excuteUpdate(sql, params);
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
return false;
@Override
public boolean updateById(int id, Good good) throws ClassNotFoundException
String sql = "update good set name=?,price=?,stock=?,count=?,imgUrl=?,type=? where id=?";
Object[] params = good.getName(),good.getPrice(),good.getStock(),good.getCount(),good.getImgUrl(),good.getType(),id;
return DBUtil.excuteUpdate(sql, params);
@Override
public boolean deleteById(int id)
String sql = "delete from good where id=?";
Object[] params = id;
try
return DBUtil.excuteUpdate(sql, params);
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
return false;
@Override
public Good queryById(int id以上是关于使用泛型实现工具类功能的主要内容,如果未能解决你的问题,请参考以下文章