All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.buession.dao.AbstractMyBatisDao Maven / Gradle / Ivy

There is a newer version: 2.3.3
Show newest version
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * =================================================================================================
 *
 * This software consists of voluntary contributions made by many individuals on behalf of the
 * Apache Software Foundation. For more information on the Apache Software Foundation, please see
 * .
 *
 * +------------------------------------------------------------------------------------------------+
 * | License: http://www.apache.org/licenses/LICENSE-2.0.txt 										|
 * | Author: Yong.Teng  													|
 * | Copyright @ 2013-2022 Buession.com Inc.														|
 * +------------------------------------------------------------------------------------------------+
 */
package com.buession.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.buession.beans.BeanUtils;
import com.buession.core.utils.FieldUtils;
import com.buession.core.utils.Assert;
import com.buession.core.utils.RandomUtils;
import com.buession.core.validator.Validate;
import com.buession.lang.Order;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.buession.core.Pagination;
import com.buession.core.exception.OperationException;

/**
 * MyBatis Data Access Object 抽象类
 *
 * @param 

* 注解类型 * @param * 实体类 * * @author Yong.Teng */ public abstract class AbstractMyBatisDao extends AbstractDao implements MyBatisDao { /** * master SqlSessionTemplate */ @Resource protected SqlSessionTemplate masterSqlSessionTemplate; /** * slave SqlSessionTemplate */ @Resource protected List slaveSqlSessionTemplates; private final static Logger logger = LoggerFactory.getLogger(AbstractMyBatisDao.class); /** * 返回 master SqlSessionTemplate * * @return master SqlSessionTemplate */ public SqlSessionTemplate getMasterSqlSessionTemplate(){ return masterSqlSessionTemplate; } /** * 设置 master SqlSessionTemplate * * @param masterSqlSessionTemplate * master SqlSessionTemplate */ public void setMasterSqlSessionTemplate(final SqlSessionTemplate masterSqlSessionTemplate){ this.masterSqlSessionTemplate = masterSqlSessionTemplate; } /** * 返回 slave SqlSessionTemplate * * @return slave SqlSessionTemplate */ public List getSlaveSqlSessionTemplates(){ return slaveSqlSessionTemplates; } /** * 设置 slave SqlSessionTemplate * * @param slaveSqlSessionTemplates * slave SqlSessionTemplate */ public void setSlaveSqlSessionTemplates(final List slaveSqlSessionTemplates){ this.slaveSqlSessionTemplates = slaveSqlSessionTemplates; } @Override public int insert(E e){ return getMasterSqlSessionTemplate().insert(getStatement(DML.INSERT), e); } @Override public int replace(E e){ return getMasterSqlSessionTemplate().insert(getStatement(DML.REPLACE), e); } @Override @SuppressWarnings("unchecked") public int update(E e, Map conditions){ Assert.isNull(e, "The data could not be empty for update."); Map data = new HashMap<>(conditions == null ? 16 : conditions.size()); if(conditions != null){ data.putAll(conditions); } Map eMap; if(e instanceof Map){ eMap = (Map) e; }else{ eMap = new HashMap<>(); BeanUtils.copyProperties(eMap, e); } eMap.forEach((key, value)->{ data.put(key.toString(), value); }); return getMasterSqlSessionTemplate().update(getStatement(DML.UPDATE), data); } @Override public int updateByPrimary(P primary, E e){ updatePrimary(e, primary); return getMasterSqlSessionTemplate().update(getStatement(DML.UPDATE_BY_PRIMARY), e); } @Override public E getByPrimary(P primary){ try{ return getSlaveSqlSessionTemplate().selectOne(getStatement(DML.GET_BY_PRIMARY), primary); }catch(OperationException e){ logger.error(e.getMessage()); } return null; } @Override public E selectOne(Map conditions, int offset, Map orders){ final Map parameters = buildParameters(conditions); if(orders != null){ parameters.put(ORDERS_PARAMETER_NAME, orders); } try{ return getSlaveSqlSessionTemplate().selectOne(getStatement(DML.SELECT_ONE), parameters); }catch(OperationException e){ logger.error(e.getMessage()); } return null; } @Override public List select(Map conditions, Map orders){ final Map parameters = buildParameters(conditions); if(orders != null){ parameters.put(ORDERS_PARAMETER_NAME, orders); } try{ return getSlaveSqlSessionTemplate().selectList(getStatement(DML.SELECT), parameters); }catch(OperationException e){ logger.error(e.getMessage()); } return null; } @Override public List select(Map conditions, int offset, int size, Map orders){ Assert.isNegative(offset, "Offset argument value could not be negative integer"); Assert.isZeroNegative(size, "Size argument value must be positive integer"); final Map parameters = buildParameters(conditions); if(orders != null){ parameters.put(ORDERS_PARAMETER_NAME, orders); } try{ return getSlaveSqlSessionTemplate().selectList(getStatement(DML.SELECT), parameters, new RowBounds(offset, size)); }catch(OperationException e){ logger.error(e.getMessage()); } return null; } @Override public Pagination paging(Map conditions, int page, int pagesize, Map orders){ Assert.isZeroNegative(page, "Page argument value must be positive integer"); Assert.isZeroNegative(pagesize, "Pagesize argument value must be positive integer"); long totalRecords = count(conditions); com.buession.dao.Pagination pagination = new com.buession.dao.Pagination<>(page, pagesize, totalRecords); if(totalRecords > 0){ List result = select(conditions, pagination.getOffset(), pagination.getPagesize(), orders); pagination.setData(result); } return pagination; } @Override public List getAll(){ try{ return getSlaveSqlSessionTemplate().selectList(getStatement(DML.GET_ALL)); }catch(OperationException e){ logger.error(e.getMessage()); } return null; } @Override public long count(){ try{ return getSlaveSqlSessionTemplate().selectOne(getStatement("count")); }catch(OperationException e){ logger.error(e.getMessage()); } return 0L; } @Override public long count(Map conditions){ try{ return getSlaveSqlSessionTemplate().selectOne(getStatement("count"), conditions); }catch(OperationException e){ logger.error(e.getMessage()); } return 0L; } @Override public int delete(Map conditions){ return getMasterSqlSessionTemplate().delete(getStatement(DML.DELETE), conditions); } @Override public int deleteByPrimary(P primary){ return getMasterSqlSessionTemplate().delete(getStatement(DML.DELETE_BY_PRIMARY), primary); } @Override public int clear(){ return getMasterSqlSessionTemplate().delete(getStatement(DML.CLEAR)); } @Override public int truncate(){ return getMasterSqlSessionTemplate().delete(getStatement(DML.TRUNCATE)); } protected final SqlSessionTemplate getSlaveSqlSessionTemplate(final int index) throws OperationException{ if(Validate.isEmpty(slaveSqlSessionTemplates)){ return getMasterSqlSessionTemplate(); }else{ SqlSessionTemplate sqlSessionTemplate = slaveSqlSessionTemplates.get(index); if(sqlSessionTemplate == null){ throw new OperationException("Could not find the \"" + index + "\" slave SqlSessionTemplate."); } return sqlSessionTemplate; } } protected final SqlSessionTemplate getSlaveSqlSessionTemplate() throws OperationException{ if(Validate.isEmpty(slaveSqlSessionTemplates)){ return getMasterSqlSessionTemplate(); }else if(slaveSqlSessionTemplates.size() == 1){ return getSlaveSqlSessionTemplate(0); }else{ int index = RandomUtils.nextInt(slaveSqlSessionTemplates.size()); return getSlaveSqlSessionTemplate(index); } } @SuppressWarnings("unchecked") protected void updatePrimary(E e, P primary){ final Collection resultMaps = masterSqlSessionTemplate.getConfiguration().getResultMaps(); if(Validate.isEmpty(resultMaps)){ return; } for(ResultMap resultMap : resultMaps){ if(e.getClass().equals(resultMap.getType())){ List resultMappings = resultMap.getIdResultMappings(); if(Validate.isNotEmpty(resultMappings)){ for(ResultMapping resultMapping : resultMappings){ try{ FieldUtils.writeField(e, resultMapping.getProperty(), primary, true); }catch(IllegalAccessException ex){ if(logger.isErrorEnabled()){ logger.error("Update resultMap[{}] id field '{}' with value: [{}] failure: {}", resultMap.getId(), resultMapping.getProperty(), primary, ex.getMessage()); } } } } break; } } } protected static Map buildParameters(final Map conditions){ return conditions == null ? new LinkedHashMap<>(16) : new LinkedHashMap<>(conditions); } protected abstract String getStatement(); protected String getStatement(final DML dml){ return getStatement(dml.toString()); } protected String getStatement(final String dml){ final String statement = getStatement(); final StringBuilder sb = new StringBuilder(statement.length() + dml.length() + 1); sb.append(statement).append('.').append(dml); return sb.toString(); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy