XUtil学习之DBUtil(八)

上节 XUtil学习之DBUtil(七)中,我们罗列了对数据库操作的方法,我们这节对增删改查的具体方法做细化的分析。
没有看过 XUtil学习之DBUtil(七)的童鞋,请出门左转,或者点击以下链接:


XUtil学习之DBUtil(七)


(1)save(Object entity) 此方法用于将单个的entity对象加入到数据库中,所有对数据的操作都抛出DbException 。首先提一个概念“事件”,事件是一连串的操作行为的总称,事件有开始,也有结束。举个例子解释“事件”,取款机取钱,突然间断电,取钱的操纵只进行了开始,在没有完成取钱的操作之前该事件都算未完成 ,那么取款机就不会扣钱。对数据库的操作也是如此,
beginTransaction()用于标识事件的开始,
setTransactionSuccessful()标识事件完成,
endTransaction()标识结束事件。
createTableIfNotExist(entity.getClass())从方法名称上可以知道该方法作用在表中不存在要添加对象的情况下添加对象到数据库。方法的具体实现参考tools(工具)部分。
execNonQuery方法是执行SQL查询。见exec sql(sql执行) 部分。

public void save(Object entity) throws DbException {
        try {
            beginTransaction();

            createTableIfNotExist(entity.getClass());
            execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity));

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }

(2)saveAll(List< > entities)
内容和save一样,只是传入的是对象的集合,需要做的操作就是循环,逐一添加,不再赘述。

 public void saveAll(List<?> entities) throws DbException {
        if (entities == null || entities.size() == 0) return;
        try {
            beginTransaction();

            createTableIfNotExist(entities.get(0).getClass());
            for (Object entity : entities) {
                execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity));
            }

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }

(3)saveBindingId(Object entity)

 将当前的对象按id自增的方式添加到表中
private boolean saveBindingIdWithoutTransaction(Object entity) throws DbException {
        Class<?> entityType = entity.getClass();
        //根据对象和注解获取到表名 
        Table table = Table.get(this, entityType);
        Id idColumn = table.id;
       //id是否自增长 
        if (idColumn.isAutoIncrement()) {
            execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity));
            //获取表最后一条数据的id
            long id = getLastAutoIncrementId(table.tableName);
            if (id == -1) {
                return false;
            }
            idColumn.setAutoIncrementId(entity, id);
            return true;
        } else {
            execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity));
            return true;
        }
    }

(4)saveBindingIdAll(List< > entities)

  public void saveBindingIdAll(List<?> entities) throws DbException {
        if (entities == null || entities.size() == 0) return;
        try {
            beginTransaction();

            createTableIfNotExist(entities.get(0).getClass());
            for (Object entity : entities) {
                if (!saveBindingIdWithoutTransaction(entity)) {
                    throw new DbException("saveBindingId error, transaction will not commit!");
                }
            }

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }

(5)saveOrUpdate(Object entity)
如果添加对象数据库中存在就更新数据,否则就添加

  public void saveOrUpdate(Object entity) throws DbException {
        try {
            beginTransaction();

            createTableIfNotExist(entity.getClass());
            saveOrUpdateWithoutTransaction(entity);

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }

(6)saveOrUpdateAll(List< > entities)
如果添加对象数据库中存在就更新数据,否则就添加,操作对象是集合,循环,赋值。

  public void saveOrUpdateAll(List<?> entities) throws DbException {
        if (entities == null || entities.size() == 0) return;
        try {
            beginTransaction();

            createTableIfNotExist(entities.get(0).getClass());
            for (Object entity : entities) {
                saveOrUpdateWithoutTransaction(entity);
            }

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.parddu.dao; import java.io.IOException; import java.sql.*; import java.util.Properties; /** * 数据库功能类 * @author parddu * @version Sep 29, 2010 9:49:31 AM */ class DButil { private String driver=null; //驱动 private String dbName=null; //数据库名 private String host=null; //主机名 private String point=null; //端口 private String userName=null; //登录帐号 private String userPass=null; //登录密码 private static DButil info = null; private DButil(){} /** * 初始化方法,加载数据库连接信息 * @throws IOException */ private static void init() throws IOException{ Properties prop = new Properties(); prop.load(DButil.class.getResourceAsStream("/db_config.properties")); info = new DButil(); info.driver = prop.getProperty("driver"); info.dbName = prop.getProperty("dbName"); info.host = prop.getProperty("host"); info.point = prop.getProperty("point"); info.userName = prop.getProperty("userName"); info.userPass = prop.getProperty("userPass"); } /** * 得到数据库连接对象 * @return 数据库连接对象 */ static Connection getConn(){ Connection conn=null; if(info == null){ try { init(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } if(info!=null){ try { Class.forName(info.driver); String url="jdbc:sqlserver://" + info.host + ":" + info.point + ";databaseName=" + info.dbName; conn=DriverManager.getConnection(url,info.userName,info.userPass); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } else{ throw new RuntimeException("读取数据库配置信息异常!"); } return conn; } /** * 关闭查询数据库访问对象 * @param rs 结果集 * @param st 上下文 * @param conn 连接对象 */ static void closeConn(ResultSet rs, Statement st,Connection conn){ try { rs.close(); } catch (Exception e) {} try { st.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } /** * 关闭增、删、该数据库访问对象 * @param st 上下文对象 * @param conn 连接对象 */ static void closeConn(Statement st ,Connection conn){ try{ st.close(); conn.close(); }catch(Exception e){} } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值