如果不想整spring的一套堆jar包,java连接mysql有一个很优雅的ORM,它的名字叫dbutils,最新版是1.8.1,而整个jar包只有87kb,但是能够完全满足增删改查的操作
下载地址在这里:DbUtils – Download Apache Commons DbUtilshttps://commons.apache.org/dbutils/download_dbutils.cgi先建一个公共的DaoUtils,有些方法是参考了网络的,代码如下:
package net.mbzj.utils;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
public class DaoUtils {
@SuppressWarnings("unchecked")
public static <T> List<T> queryForList(String sql,Object[] param,Class<T> clazz){
List<T> obj = null;
Connection conn = null;
QueryRunner qRunner = new QueryRunner();
try {
conn = JDBCPoolUtils.getConnection();
List<T> query = (List<T>)qRunner.query(conn,sql,new BeanListHandler<Object>(clazz),param);
obj = query;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return obj;
}
public static <T> boolean create(String sql,Object parm[]) {
Connection conn =null;
QueryRunner qr = new QueryRunner();
boolean flag = false;
try {
conn = JDBCPoolUtils.getConnection();
qr.update(conn,sql,parm);
flag = true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return flag;
}
public static <T> boolean create(String sql,Object parm[],Connection conn) throws SQLException{
//多表操作在外面关闭conn
QueryRunner qr = new QueryRunner();
boolean flag = false;
qr.update(conn,sql,parm);
flag = true;
return flag;
}
public static <T> long save(String sql,Object parm[])throws SQLException{
//BigInteger a = null ;
long a = 0;
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
try {
qr.insert(conn,sql,new ScalarHandler<Object>(), parm );
a =((BigInteger) qr.query(conn, "SELECT LAST_INSERT_ID()",new ScalarHandler<Object>(1 ))).longValue();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return a;
}
public static <T> long save(String sql,Object parm[],Connection conn) throws SQLException{
//BigInteger a = null ;
long a = 0;
QueryRunner qr = new QueryRunner();
qr.insert(conn,sql,new ScalarHandler<Object>(), parm );
a =((BigInteger) qr.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<Object>(1))).longValue();
return a;
}
public static <T> String save2(String sql,Object parm[])throws SQLException{
//BigInteger a = null ;
String a = null;
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
try {
qr.insert(conn,sql,new ScalarHandler<Object>(), parm );
a =((String) qr.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<Object>(1)));
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return a;
}
public static <T> T findById(String sql,Object[] param,Class<T> clazz){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qRunner = new QueryRunner();
T t = null;
try {
t= (T)qRunner.query(conn,sql,new BeanHandler(clazz),param);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return t;
}
public static <T> T findByCondition(String sql,Object[] param,Class<T> clazz){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qRunner = new QueryRunner();
T t = null;
try {
t= (T)qRunner.query(conn,sql,new BeanHandler(clazz),param);
} catch (SQLException e) {
e.printStackTrace();
}finally {
DbUtils.closeQuietly(conn);
}
return t;
}
public static Map<String, Object> findMap(String sql,Object[] param){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qRunner = new QueryRunner();
Map<String, Object> map = new HashMap<String, Object>();
try {
map= (Map<String, Object>) qRunner.query(conn,sql, new MapHandler(),param);
} catch (SQLException e) {
e.printStackTrace();
}finally {
DbUtils.closeQuietly(conn);
}
return map;
}
public static <T> boolean update(String sql,Object[] param)throws SQLException{
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
boolean flag = false;
try {
qr.update(conn,sql, param );
flag = true;
} catch (SQLException e) {
throw e;
} finally {
DbUtils.closeQuietly(conn);
}
return flag;
}
public static <T> boolean modify(String sql,Object[] param) throws SQLException{
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr=new QueryRunner();
boolean flag = false;
try {
qr.update(conn,sql,param);
flag = true;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DbUtils.closeQuietly(conn);
}
return flag;
}
public static <T> boolean modify(String sql,Object[] param,Connection conn ) throws SQLException {
QueryRunner qr=new QueryRunner();
boolean flag = false;
qr.update(conn,sql,param);
flag = true;
return flag;
}
public static void del(String sql,long id){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
try {
qr.update(conn,sql,id );
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
public static void del(String sql,String id){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
try {
qr.update(conn,sql,id );
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
public static void delAll(String sql){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
try {
qr.update(conn,sql );
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
public int insertForKeys(String sql, Object[] params) {
int key = 0;
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn = JDBCPoolUtils.getConnection();
try {
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ParameterMetaData pmd = stmt.getParameterMetaData();
if (params.length < pmd.getParameterCount()) {
throw new SQLException("主键返回:" + pmd.getParameterCount());
}
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
key = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return key;
}
private static ScalarHandler scalarHandler = new ScalarHandler() {
@Override
public Object handle(ResultSet rs) throws SQLException {
Object obj = super.handle(rs);
if (obj instanceof BigInteger)
return ((BigInteger) obj).longValue();
return obj;
}
};
public static int[] batchUpdate(String sql, Object[][] params) {
int[] affectedRows = new int[0];
Connection conn = null;
try {
conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
affectedRows = qr.batch(conn,sql, params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return affectedRows;
}
public static int[] batchUpdate(String sql, Object[][] params,Connection conn) throws SQLException {
int[] affectedRows = new int[0];
QueryRunner qr = new QueryRunner();
affectedRows = qr.batch(conn,sql, params);
return affectedRows;
}
public static int count(String sql, Object... params) {
Number num = 0;
Connection conn = null;
try {
conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
if (params == null) {
num = (Number) qr.query(conn,sql, scalarHandler);
} else {
num = (Number) qr.query(conn,sql, scalarHandler, params);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return (num != null) ? num.intValue() : -1;
}
public static int count(String sql, Criteria cri) {
Number num = 0;
Connection conn = null;
try {
conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
List<Criteria.Item> l = cri.items;
StringBuffer s = new StringBuffer();
int m=0;
for(int i=0;i<l.size();i++) {
Criteria.Item ci = l.get(i);
if(ci.getOp().equals(cri.CUSTOM)) {
l.remove(i);
}
}
Object param[] = new Object[cri.items.size()];
for(Criteria.Item i:l){
s.append((String)i.getValue());
if(m<l.size()){
s.append(",");
}
param[m] = (String)i.getValue();
m++;
}
if(l.size()>0){
//1Object params[] = {s.toString()};
num = (Number) qr.query(conn,sql, scalarHandler, param);
}else{
num = (Number) qr.query(conn,sql, scalarHandler);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return (num != null) ? num.intValue() : -1;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> List<T> list(String sql,Criteria cri,Class<T> clazz){
List<T> obj = null;
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qRunner = new QueryRunner();
try {
List<Criteria.Item> l = cri.items;
for(int i=0;i<l.size();i++) {
Criteria.Item ci = l.get(i);
//System.out.println("ci---->"+ci.getValue());
if(ci.getOp().equals(cri.CUSTOM)) {
l.remove(i);
}
}
//System.out.println(l.size());
StringBuffer s = new StringBuffer();
int m=0;
Object param[] = new Object[cri.items.size()];
for(Criteria.Item i:l){
s.append((String)i.getValue());
if(m<l.size()){
s.append(",");
}
//System.out.println(l.get(m).getOp()+"cil----->"+l.get(m).getValue());
param[m]=(String)i.getValue();
m++;
}
if(cri.items.size()>0){
obj = (List<T>)qRunner.query(conn,sql,new BeanListHandler(clazz),param);
DbUtils.closeQuietly(conn);
}else{
obj = (List<T>)qRunner.query(conn,sql,new BeanListHandler(clazz),param);
DbUtils.closeQuietly(conn);
}
} catch (SQLException e) {
e.printStackTrace();
DbUtils.closeQuietly(conn);
}
return obj;
}
/**
* 根据id数组批量删除
* @param sql
* @throws SQLException
*/
public static void delAll(String sql,long[] id) {
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr=new QueryRunner();
try {
for(int i=0;i<id.length;i++) {
qr.update(conn,sql,id[i]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
DbUtils.closeQuietly(conn);
}finally {
DbUtils.closeQuietly(conn);
}
}
/**
* 根据id数组批量删除
* @param sql
* @throws SQLException
*/
public static void delAll(String sql,String[] id) {
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr=new QueryRunner();
try {
for(int i=0;i<id.length;i++) {
qr.update(conn,sql,id[i]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
DbUtils.closeQuietly(conn);
}finally {
DbUtils.closeQuietly(conn);
}
}
public static List<Map<String,Object>> listMap(String sql) {
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qRunner = new QueryRunner();
try {
List<Map<String,Object>> list = (List<Map<String, Object>>) qRunner.query(conn,sql,new LinkMapListHandler());
return list;
}catch(Exception e) {
e.printStackTrace();
}finally {
DbUtils.closeQuietly(conn);
}
return null;
}
@SuppressWarnings("unchecked")
public static Object sum(String sql,Object parm[]){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
Object o = null;
try {
o = (Object) qr.query(conn,sql, scalarHandler,parm);
if(null==o) {
o="0";
}
return o;
} catch (SQLException e) {
e.printStackTrace();
DbUtils.closeQuietly(conn);
} finally {
DbUtils.closeQuietly(conn);
}
return o;
}
@SuppressWarnings("unchecked")
public static Object max(String sql,Object parm[]){
Connection conn = JDBCPoolUtils.getConnection();
QueryRunner qr = new QueryRunner();
Object o = null;
try {
o = (Object) qr.query(conn,sql, scalarHandler,parm);
if(null==o) {
o="0";
}
return o;
} catch (SQLException e) {
e.printStackTrace();
DbUtils.closeQuietly(conn);
} finally {
DbUtils.closeQuietly(conn);
}
return o;
}
}
这个类满足了jdbc的所有操作
如果调用这个类,现以文章管理为例子,集成增加、修改、查询、删除
新建一个ArticleDao
package net.mbzj.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import net.mbzj.bean.Article;
import net.mbzj.bean.Title;
import net.mbzj.utils.Criteria;
import net.mbzj.utils.DaoUtils;
import net.mbzj.utils.DateUtils;
import net.mbzj.utils.JDBCPoolUtils;
import net.mbzj.utils.StringUtils;
public class ArticleDao extends DaoUtils{
private static final String SELECT_TITLE = "SELECT t1.id,t1.siteId,t1.categoryId,t1.sort,t1.title,t1.shortTitle,t1.status,t1.attr,t1.author,t1.logo,t1.icon,t1.type,t1.keywords,t1.description,t1.click,t1.createBy,t1.createTime,t1.updateBy,t1.updateTime,t1.isJump,t1.jumpUrl,t1.userId FROM mj_title t1 ";
private static final String SELECT_ALL = "SELECT t1.id,t1.siteId,t1.categoryId,t1.sort,t1.title,t1.shortTitle,t1.status,t1.attr,t1.author,t1.logo,t1.icon,t1.type,t1.keywords,t1.description,t1.click,t1.createBy,t1.createTime,t1.updateBy,t1.updateTime,t1.isJump,t1.jumpUrl,t2.content,t1.userId FROM mj_title t1,mj_article t2 ";
public static Article findById(long id){
StringBuilder sql = new StringBuilder(SELECT_ALL);
sql.append(" where t1.id=t2.titleId AND t1.id=?");
Article a = (Article)findById(sql.toString(), new Object[]{id}, Article.class);
return a;
}
public static Title findByTitle(String title,long siteId){
StringBuilder sql = new StringBuilder(SELECT_TITLE);
sql.append(" where t1.title=? and t1.siteId=?");
Title a = (Title)findById(sql.toString(), new Object[]{title,siteId}, Title.class);
return a;
}
public static void dels(String ids[]){
delAll("delete from mj_title where id=?",ids);
delAll("delete from mj_article where titleId=?",ids);
}
public static void del(long id){
del("delete from mj_title where id=?",id);
del("delete from mj_article where titleId=?",id);
}
public static long save(Article a) throws Exception{
Connection conn = null;
long titleId = 0;
//long articleId = 0;
try {
conn = JDBCPoolUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
Object paramTitle[] = {a.getSiteId(),a.getCategoryId(),a.getSort(),a.getTitle(),a.getStatus(),a.getAttr(),a.getShortTitle(),a.getAuthor(),a.getLogo(),a.getIcon(),a.getType(),a.getKeywords(),a.getDescription(),a.getCreateBy(), DateUtils.format(a.getCreateTime(), DateUtils.C_TIME_PATTERN_DEFAULT),a.getIsJump(),a.getJumpUrl(),a.getClick(),a.getUserId()};
titleId = save("INSERT INTO mj_title(siteId,categoryId,sort,title,status,attr,shortTitle,author,logo,icon,type,keywords,description,createBy,createTime,isJump,jumpUrl,click,userId) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",paramTitle,conn);
Object paramArticle[] = {titleId,a.getContent()};
save("insert into mj_article(titleId,content) values(?,?)", paramArticle,conn);
DbUtils.commitAndClose(conn);
}catch(Exception e) {
e.printStackTrace();
DbUtils.rollback(conn);
}finally{
DbUtils.closeQuietly(conn);
}
return titleId;
}
//update title and content
public static boolean update(Article a)throws SQLException{
Connection conn = null;
boolean flag = false;
try {
conn = JDBCPoolUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
Object paramTitle[] = {a.getTitle(),a.getStatus(),a.getAttr(),a.getShortTitle(),a.getKeywords(),a.getDescription(),a.getLogo(),a.getIcon(),a.getCategoryId(),a.getAuthor(),a.getSort(),DateUtils.format(a.getCreateTime(), DateUtils.C_TIME_PATTERN_DEFAULT),a.getUpdateBy(),a.getIsJump(),a.getJumpUrl(),a.getId()};
Object paramArticle[] = {a.getContent(),a.getId()};
modify("update mj_title set title=?,status=?,attr=?,shortTitle=?,keywords=?,description=?,logo=?,icon=?,categoryId=?,author=?,sort=?,createTime=?,updateTime=now(),updateBy=?,isJump=?,jumpUrl=? where id=?",paramTitle,conn);
modify("update mj_article set content=? where titleId=?",paramArticle,conn);
flag = true;
if(flag) {
DbUtils.commitAndClose(conn);
}
}catch(Exception e) {
e.printStackTrace();
DbUtils.rollback(conn);
}finally{
DbUtils.closeQuietly(conn);
}
return flag;
}
public static void updateStatus(int status,long id) throws SQLException{
update("update mj_title set status=? where id=?",new Object[] {status,id});
}
public static List<Title> page(Criteria cri){
StringBuilder sql = new StringBuilder(SELECT_TITLE);
String condition = cri.getCondition(2);
if (StringUtils.isNotBlank(condition)){
sql.append(condition);
}
if (cri.getOrderBy().length() == 0) {
sql.append(" ORDER BY createTime DESC ");
}else{
sql.append(cri.getOrderBy());
}
sql.append(" LIMIT " + (cri.getPageNo() - 1) * cri.getPageSize() + "," + cri.getPageSize());
System.out.println(cri.getCondition());
System.out.println(sql);
List<Title> list = list(sql.toString(), cri, Title.class);
return list;
}
public static List<Title> page2(Criteria cri,String attrs){
StringBuilder sql = new StringBuilder(SELECT_TITLE);
String condition = cri.getCondition(2);
if (StringUtils.isNotBlank(condition)){
sql.append(condition);
}
if(StringUtils.isNotEmpty(attrs)&&!attrs.equals("null")) {
sql.append(" and t1.status=1 and CONCAT (',',attr,',') REGEXP ',("+attrs+"),' ");
}else {
sql.append(" and t1.status=1 ");
}
if (cri.getOrderBy().length() == 0) {
sql.append(" ORDER BY createTime DESC ");
}else{
sql.append(cri.getOrderBy());
}
sql.append(" LIMIT " + (cri.getPageNo() - 1) * cri.getPageSize() + "," + cri.getPageSize());
System.out.println(cri.getCondition());
System.out.println(sql);
List<Title> list = list(sql.toString(), cri, Title.class);
return list;
}
public static List<Title> listAll(Criteria cri){
StringBuilder sql = new StringBuilder(SELECT_TITLE);
String condition = cri.getCondition(2);
if (StringUtils.isNotBlank(condition)){
sql.append(condition);
}
if (cri.getOrderBy().length() == 0) {
sql.append(" ORDER BY createTime DESC ");
}else{
sql.append(cri.getOrderBy());
}
//sql.append(" LIMIT " + (cri.getPageNo() - 1) * cri.getPageSize() + "," + cri.getPageSize());
//System.out.println(sql);
List<Title> list = list(sql.toString(), cri, Title.class);
return list;
}
public static int countTotal(Criteria cri){
StringBuilder sql = new StringBuilder("select count(id) from mj_title t1");
String condition = cri.getCondition(2);
if (StringUtils.isNotBlank(condition)){
sql.append(condition);
}
return count(sql.toString(),cri);
}
public static void updateClick(long id)throws SQLException{
Object param[] = {id};
update("update mj_title set click=click+1 where id=?;", param);
}
//查找上一篇一下篇
public static Title findByNext(long id,long categoryId,String flag){
StringBuilder sql = new StringBuilder(SELECT_TITLE);
if(flag.equals("next")) {
sql.append(" where t1.id>? and categoryId=? order by t1.id ASC");
}else if(flag.equals("prev")) {
sql.append(" where t1.id<? and categoryId=? order by t1.id DESC");
}
Title a = (Title)findByCondition(sql.toString(), new Object[]{id,categoryId}, Title.class);
return a;
}
public static int findByMax(long siteId){
int max = 0;
StringBuilder sql = new StringBuilder("SELECT MAX(sort) as num FROM mj_title where ");
sql.append("t1.siteId=?");
Object m = max(sql.toString(), new Object[]{siteId});
System.out.println(m);
if(m==null) {
m = "0";
}
max = Integer.valueOf(m.toString());
return max;
}
public static void updateCategory(long categoryId,String ids[]) throws Exception{
Object params[][] = new Object[ids.length][2];
for (int i = 0; i < ids.length; i++) {
params[i] = new Object[] {categoryId,Long.valueOf(ids[i])};
}
String sql ="update mj_title set categoryId=? where id=? ";
batchUpdate(sql, params);
}
public static boolean updateSort(int sort,long id) throws SQLException{
return update("update mj_title set sort=? where id=?",new Object[] {sort,id});
}
}
结合上面讲到的Servlet知识,你会发现,在Servlet中,如果要调用ArticleDao也非常简单,一行代码轻松调用文章内容
Article a = ArticleDao.findById(Long.valueOf(p0));
调用效果如下,这样一个简单的MVC流程就走通了:
简约稳重毕业答辩通用ppt模板 - 模板之家简约稳重毕业答辩通用ppt模板https://www.mbzj.net/article/view/562