mybatis spring配置SqlSessionTemplate的使用方式

mybatis spring配置SqlSessionTemplate使用

1.application.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
 xmlns:lang="http://www.springframework.org/schema/lang"
 xmlns:top="http://www.comtop.org/schema/spring-top"
 xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.directwebremoting.org/schema/spring-dwr
          http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
          http://www.springframework.org/schema/lang
          http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
          http://www.comtop.org/schema/spring-top
          http://www.comtop.org/schema/top/spring-top.xsd">

 <!-- spring 注解 -->
    <context:component-scan base-package="com.dwr"/>

    <!-- 这句的作用是表示允许DWR访问Spring的Context -->
 <dwr:annotation-config  id="dwr_as"/>
    <!-- 扫描加了注解@RemoteProxy & @RemoteMethod 的对象 -->
    <dwr:annotation-scan scanRemoteProxy="false" base-package="com.dwr" />
    <!-- dwr初始化配置 -->
    <dwr:configuration></dwr:configuration>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
       destroy-method="close">
       <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
       <property name="url" value="jdbc:oracle:thin:@10.10.15.29:1521:xxxx" />
       <property name="username" value="edmp" />
       <property name="password" value="edmp" />
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath:com/mybatis/*.xml" />
    </bean>
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
 </bean>
 <import resource="RESTful.xml" />
</beans>

2.MyBatisDAO :

package com.dwr;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MyBatisDAO{

 @Resource
    private SqlSessionTemplate sqlSessionTemplate;  

    public MyBatisDAO() {
    }  

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }  

    public void delete(String statementId, Object deleteObject) {
        try {
            this.sqlSessionTemplate.delete(statementId, deleteObject);
        } catch (Exception e) {
        }
    }  

    public void insert(String statementId, Object insertObject) {
        try {
            this.sqlSessionTemplate.insert(statementId, insertObject);
        } catch (Exception e) {
        }
    }    

    public void update(String statementId, Object updateObject) {
        try {
            this.sqlSessionTemplate.update(statementId, updateObject);
        } catch (Exception e) {
        }
    }    

    public Object getObject(String statementId, Object selectParamObject) {
        return this.sqlSessionTemplate
                .selectOne(statementId, selectParamObject);
    }  

    @SuppressWarnings("all")
    public List queryList(String statementId, Object queryParamObject) {
        return this.sqlSessionTemplate
                .selectList(statementId, queryParamObject);
    }
    @SuppressWarnings("all")
    public List queryList(String statementId, Object queryParamObject,
            int pageNo, int pageSize) {
        RowBounds objRowBounds;
        int iOffset = (pageNo - 1) * pageSize;
        objRowBounds = new RowBounds(iOffset, pageSize);
        return this.sqlSessionTemplate.selectList(statementId,
                queryParamObject, objRowBounds);
    }
}  

3.mybatis配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
    "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="Test">
 <select id="queryDataCount"
  parameterType="com.mybatis.Test"
  resultType="int">
  SELECT COUNT(1) FROM INF_CONSUMER T WHERE T.UUID = #{uuid}
 </select>
</mapper>

4.具体DAO配置

package com.dwr;
import org.springframework.stereotype.Repository;
import com.mybatis.Test;
@Repository
public class TestDAO extends MyBatisDAO {
 public int getCount(Test test) {
  return (Integer) this.getObject("Test.queryDataCount", test);
 }
}

MyBatis+SpringBoot整合 注入SqlSessionTemplate

实际开发中我们操作数据库持久化,总是需要写重复的mapper,service,xml浪费了我们大量的时间,在这里推荐大家使用SqlSessionTemplate废话不多说直接上代码

工具类接口层:

package com.miaosuan.dao;
import java.util.List;
import com.miaosuan.dao.dbenums.NameSpaceEnum;
/**
 * 数据库操作接口
 *
 * @param <T> 传入参数
 * @param <E> 返回结果
 * @author qin_wei
 */
public interface DBDao {
    <T, E> E select(NameSpaceEnum namespace, String id, T params);
    <T, E> List<E> selectList(NameSpaceEnum namespace, String id, T params);
    <T> int update(NameSpaceEnum namespace, String id, T params);
    <T> List<Long> updateList(NameSpaceEnum namespace, String id, List<T> list);
    <T> long insert(NameSpaceEnum namespace, String id, T params);
    <T> List<Long> insertList(NameSpaceEnum namespace, String id, List<T> list);
    <T> int delete(NameSpaceEnum namespace, String id, T params);
    <T> List<Long> deleteList(NameSpaceEnum namespace, String id, List<T> list);
    <T> void batchALL(NameSpaceEnum namespace, String id, List<T> params, Integer bathcount);
}

实现类:

package com.miaosuan.dao;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import com.miaosuan.common.util.NullEmptyUtil;
import com.miaosuan.common.util.StringUtil;
import com.miaosuan.dao.dbenums.NameSpaceEnum;
import com.miaosuan.logger.Log;
@Repository("dbDao")
@Scope("prototype")
public class BaseDao implements DBDao {
    @Autowired
    SqlSessionTemplate sqlSessionTemplate;
    @Override
    public <T, E> E select(NameSpaceEnum namespace, String id, T params) {
        if (params == null) {
            return sqlSessionTemplate.selectOne(namespace.mapper + "." + id);
        } else {
            return sqlSessionTemplate.selectOne(namespace.mapper + "." + id, params);
        }
    }
//这个主要用来批量操作
    @Override
    public <T, E> List<E> selectList(NameSpaceEnum namespace, String id, T params) {
        if (params == null) {
            return sqlSessionTemplate.selectList(namespace.mapper + "." + id);
        } else {
            return sqlSessionTemplate.selectList(namespace.mapper + "." + id, params);
        }
    }
    @Override
    public <T> int update(NameSpaceEnum namespace, String id, T params) {
        if (params == null) {
            return sqlSessionTemplate.update(namespace.mapper + "." + id);
        } else {
            return sqlSessionTemplate.update(namespace.mapper + "." + id, params);
        }
    }
    @SuppressWarnings("unchecked")
    @Override
    public <T> List<Long> updateList(NameSpaceEnum namespace, String id, List<T> list) {
        try {
            if (list == null || list.isEmpty()) {
                return null;
            }
            MappedStatement ms = sqlSessionTemplate.getConfiguration().getMappedStatement(namespace.mapper + "." + id);
            SqlCommandType sqlCommandType = ms.getSqlCommandType();
            BoundSql boundSql = ms.getSqlSource().getBoundSql(list.get(0));
            String sql = boundSql.getSql();
            List<ParameterMapping> list2 = boundSql.getParameterMappings();
            Connection connection = sqlSessionTemplate.getConnection();
            PreparedStatement statement = null;
            if (sqlCommandType == SqlCommandType.INSERT) {
                statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            } else {
                statement = connection.prepareStatement(sql);
            }
            for (T item : list) {
                if (NullEmptyUtil.isEmpty(item)) {
                    continue;
                }
                if (item instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) item;
                    for (int index = 0; index < list2.size(); index++) {
                        ParameterMapping pm = list2.get(index);
                        Object value = map.get(pm.getProperty());
                        statement.setObject(index + 1, value);
                    }
                } else if (item instanceof Long || item instanceof String || item instanceof Integer) {
                    statement.setObject(1, item);
                } else {
                    for (int index = 0; index < list2.size(); index++) {
                        ParameterMapping pm = list2.get(index);
                        String methodName = StringUtil.hump("get_" + pm.getProperty(), "_");
                        Method method = item.getClass().getMethod(methodName);
                        Object value = method.invoke(item);
                        statement.setObject(index + 1, value);
                    }
                }
                statement.addBatch();
            }
            List<Long> resultList = new ArrayList<Long>();
            int[] resultArray = statement.executeBatch();
            if (sqlCommandType != SqlCommandType.INSERT) {
                for (int intval : resultArray) {
                    resultList.add(Long.valueOf(intval + ""));
                }
            } else {
                ResultSet resultSet = statement.getGeneratedKeys();
                while (resultSet.next()) {
                    resultList.add(resultSet.getLong(0));
                }
            }
            return resultList;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    @Override
    public <T> long insert(NameSpaceEnum namespace, String id, T params) {
        return update(namespace, id, params);
    }
    @Override
    public <T> List<Long> insertList(NameSpaceEnum namespace, String id, List<T> list) {
        return updateList(namespace, id, list);
    }
    @Override
    public <T> int delete(NameSpaceEnum namespace, String id, T params) {
        return update(namespace, id, params);
    }
    @Override
    public <T> List<Long> deleteList(NameSpaceEnum namespace, String id, List<T> list) {
        return updateList(namespace, id, list);
    }
//所有的批量都可以用这个方法,它识别的是xml的sql,与方法无关;bathcount指的是没多少条提交一次事物
    @Override
    public <T> void batchALL(NameSpaceEnum namespace, String sqlId, List<T> list, Integer bathcount) {
        List<T> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            data.add(list.get(i));
            if (data.size() == bathcount || i == list.size() - 1) {
                this.batchUtil(namespace, sqlId, data);
                data.clear();
            }
        }
    }
    @SuppressWarnings("unchecked")
    private <T> void batchUtil(NameSpaceEnum namespace, String sqlId, List<T> list) {
        try {
            if (list == null || list.isEmpty()) {
                return;
            }
            MappedStatement ms = sqlSessionTemplate.getConfiguration().getMappedStatement(namespace.mapper + "." + sqlId);
            SqlCommandType sqlCommandType = ms.getSqlCommandType();
            BoundSql boundSql = ms.getSqlSource().getBoundSql(list.get(0));
            String sql = boundSql.getSql();
            List<ParameterMapping> list2 = boundSql.getParameterMappings();
            Connection connection = sqlSessionTemplate.getSqlSessionFactory().openSession().getConnection();
            PreparedStatement statement = null;
            if (sqlCommandType == SqlCommandType.INSERT) {
                statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            } else {
                statement = connection.prepareStatement(sql);
            }
            sql = sql.replaceAll("\\n", "");
            sql = sql.replaceAll("\\t", "");
            sql = sql.replaceAll("[[ ]]{2,}", " ");
            Log.info("==>  Preparing:" + sql);
            for (T item : list) {
                if (NullEmptyUtil.isEmpty(item)) {
                    continue;
                }
                StringBuffer values = new StringBuffer();
                if (item instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) item;
                    for (int index = 0; index < list2.size(); index++) {
                        ParameterMapping pm = list2.get(index);
                        Object value = map.get(pm.getProperty());
                        values.append(value).append("(").append(value.getClass()).append("),");
                        statement.setObject(index + 1, value);
                    }
                } else if (item instanceof Long || item instanceof String || item instanceof Integer) {
                    statement.setObject(1, item);
                    values.append(item).append("(").append(StringUtils.substringAfterLast(item.getClass().toString(), ".")).append("),");
                } else {
                    List<String> params = new ArrayList<>();
                    for (int index = 0; index < list2.size(); index++) {
                        ParameterMapping pm = list2.get(index);
                        String methodName = StringUtil.hump("get_" + pm.getProperty(), "_");
                        Method method = item.getClass().getMethod(methodName);
                        Object value = method.invoke(item);
                        params.add(value.toString());
                        statement.setObject(index + 1, value);
                        values.append(value).append("(").append(StringUtils.substringAfterLast(value.getClass().toString(), ".")).append("),");
                    }
                }
                statement.addBatch();
                values.delete(values.length() - 1, values.length());
                Log.info("==> Parameters:" + values);
            }
            List<Long> resultList = new ArrayList<>();
            int[] resultArray = statement.executeBatch();
            if (sqlCommandType != SqlCommandType.INSERT) {
                for (int intval : resultArray) {
                    resultList.add(Long.valueOf(intval + ""));
                }
            } else {
                ResultSet resultSet = statement.getGeneratedKeys();
                while (resultSet.next()) {
                    try {
                        resultList.add(resultSet.getLong(1));
                    } catch (Exception e) {
                        Log.error("错误:" + e.toString());
                    }
                }
            }
            return;
        } catch (Exception e) {
            Log.error("错误:" + e.toString());
            throw new RuntimeException(e.toString());
        }
    }
    @SuppressWarnings("unchecked")
    protected <T> void printSql(String id, T params) {
        try {
            MappedStatement ms = sqlSessionTemplate.getConfiguration().getMappedStatement(id);
            BoundSql boundSql = ms.getSqlSource().getBoundSql(params);
            String sql = boundSql.getSql();
            sql = sql.replaceAll("\\n", "");
            sql = sql.replaceAll("\\t", "");
            sql = sql.replaceAll("[[ ]]{2,}", " ");
            List<ParameterMapping> list2 = boundSql.getParameterMappings();
            if (params == null) {
            } else if (params instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) params;
                for (int index = 0; index < list2.size(); index++) {
                    ParameterMapping pm = list2.get(index);
                    Object value = map.get(pm.getProperty());
                    sql = sql.replaceFirst("[?]", value + "");
                }
            } else if (params instanceof Long || params instanceof String || params instanceof Integer) {
                sql = sql.replaceFirst("[?]", params + "");
            } else {
                for (int index = 0; index < list2.size(); index++) {
                    ParameterMapping pm = list2.get(index);
                    String methodName = StringUtil.hump("get_" + pm.getProperty(), "_");
                    Method method = params.getClass().getMethod(methodName);
                    Object value = method.invoke(params);
                    sql = sql.replaceFirst("[?]", value + "");
                }
            }
            Log.info(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

说明:NameSpaceEnum指的是你的xml的映射路径,不喜欢的可以写成自己的xml所在路径,我这边用的是枚举类

sqlid指的是你xml中方法的名字,

无论是单个操作还是批量操作,你的xml中的sql都是单个,这里的批量用的并不是mybatis的foreach操作而是通过传进来的集合批量提交事务到数据库‘'

具体使用:

接口定义:

接口实现类:

xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.miaosuan.mapper.shop.shopimageinfo">//这里的路径随便写不要重复就可以
    <sql id="tableName">
       shop_image_info
    </sql>
    <sql id="where_sql">
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="spuId != null">
                and spu_id = #{spuId}
            </if>
        </where>
    </sql>

    <sql id="update_sql">
        <set>
            <if test="imageName != null and imageName != ''">
                image_name = #{imageName},
            </if>
            <if test="imageSuffix != null and imageSuffix != ''">
                image_suffix = #{imageSuffix},
            </if>
            <if test="url != null and url != ''">
                url = #{url},
            </if>
            <if test="zcyUrl != null and zcyUrl != ''">
                zcy_url = #{zcyUrl},
            </if>
            <if test="zcyStatus != null">
                zcy_status = #{zcyStatus},
            </if>
            <if test="imgType != null and imgType != ''">
                img_type = #{imgType},
            </if>
            <if test="status != null">
                status = #{status},
            </if>
            <if test="mainImg != null">
                main_img = #{mainImg},
            </if>
        </set>
    </sql>

    <select id="list" resultType="DBMap" parameterType="DBMap">
        select * from
        <include refid="tableName"/>
        <include refid="where_sql"/>
    </select>

    <select id="get" resultType="DBMap" parameterType="DBMap">
        select * from
        <include refid="tableName"/>
        <include refid="where_sql"/>
        limit 1
    </select>

    <update id="update" parameterType="DBMap">
        update
        <include refid="tableName"/>
        <include refid="update_sql"/>
        <include refid="where_sql"/>
    </update>

    <delete id="delete" parameterType="DBMap">
        delete from
        <include refid="tableName"/>
        <include refid="where_sql"/>
    </delete>

    <insert id="insert" parameterType="DBMap" keyProperty="id" useGeneratedKeys="true">
        insert into
        <include refid="tableName"/>
        (image_name,image_suffix,spu_id,url,zcy_url,zcy_status,img_type
        <if test="status != null">
            ,status
        </if>,main_img
        )
        values
        (#{imageName},#{imageSuffix},#{spuId},#{url},#{zcyUrl},#{zcyStatus},#{imgType}
        <if test="status != null">
            ,#{status}
        </if>
        ,#{mainImg}
        )
    </insert>
    <select id="selectBySpuId" resultType="DBMap" parameterType="java.lang.Long">
        select * from
        <include refid="tableName"></include>
        <where>
            and spu_id = #{spuId,jdbcType=BIGINT}
            and img_type = 0 order by main_img desc ,id desc
        </where>
    </select>
    <select id="selectIdsByShopId" resultType="java.lang.Long" parameterType="java.lang.Long">
        select id from shop_image_info
        <where>
            spu_id = #{spuId} and img_type = 0
        </where>
    </select>
    <update id="updateByPrimaryKeySelective" parameterType="DBMap">
        update shop_image_info
        <set>
            <if test="imageName != null">
                image_name = #{imageName},
            </if>
            <if test="imageSuffix != null">
                image_suffix = #{imageSuffix},
            </if>
            <if test="spuId != null">
                spu_id = #{spuId},
            </if>
            <if test="url != null">
                url = #{url},
            </if>
            <if test="zcyUrl != null">
                zcy_url = #{zcyUrl},
            </if>
            <if test="zcyStatus != null">
                zcy_status = #{zcyStatus},
            </if>
            <if test="imgType != null">
                img_type = #{imgType},
            </if>
            <if test="status != null">
                status = #{status},
            </if>
            <if test="mainImg != null">
                main_img = #{mainImg},
            </if>
        </set>
        where id = #{id}
    </update>
    <insert id="insertSelective" parameterType="DBMap">
        insert into shop_image_info
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="imageName != null">
                image_name,
            </if>
            <if test="imageSuffix != null">
                image_suffix,
            </if>
            <if test="spuId != null">
                spu_id,
            </if>
            <if test="url != null">
                url,
            </if>
            <if test="zcyUrl != null">
                zcy_url,
            </if>
            <if test="zcyStatus != null">
                zcy_status,
            </if>
            <if test="imgType != null">
                img_type,
            </if>
            <if test="status != null">
                status,
            </if>
            <if test="mainImg != null">
                main_img,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id},
            </if>
            <if test="imageName != null">
                #{imageName},
            </if>
            <if test="imageSuffix != null">
                #{imageSuffix},
            </if>
            <if test="spuId != null">
                #{spuId},
            </if>
            <if test="url != null">
                #{url},
            </if>
            <if test="zcyUrl != null">
                #{zcyUrl},
            </if>
            <if test="zcyStatus != null">
                #{zcyStatus},
            </if>
            <if test="imgType != null">
                #{imgType},
            </if>
            <if test="status != null">
                #{status},
            </if>
            <if test="mainImg != null">
                #{mainImg},
            </if>
        </trim>
    </insert>
    <delete id="batchDeleteByIds" parameterType="java.util.List">
        delete from
        <include refid="tableName"/>
        where img_type = 0 and id in
        <foreach collection="list" item="params" open="(" separator="," close=")">
            #{params}
        </foreach>
    </delete>
    <delete id="deleteById" parameterType="java.lang.Long">
        delete from
        <include refid="tableName"/>
        where img_type = 0 and id = #{params}
    </delete>
    <delete id="deleteWithoutByIds" parameterType="DBMap">
        delete from
        <include refid="tableName"/>
        where img_type = 0 and spu_id = #{spuId}
        <if test="ids != null">
            and id not in
            <foreach collection="list" item="ids" open="(" separator="," close=")">
                #{ids}
            </foreach>
        </if>
    </delete>
    <!--批量添加标准库数据照片-->
    <insert id="insertImage" parameterType="com.miaosuan.dao.entity.standard.StandardImageInfo">
        insert into
        <include refid="tableName"></include>
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="imageName != null">
                image_name,
            </if>
            <if test="imageSuffix != null">
                image_suffix,
            </if>
            <if test="spuId != null">
                spu_id,
            </if>
            <if test="url != null">
                url,
            </if>
            <if test="imgType != null">
                img_type,
            </if>
            <if test="status != null">
                status,
            </if>
            <if test="mainImg != null">
                main_img,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="imageName != null">
                #{imageName,jdbcType=VARCHAR},
            </if>
            <if test="imageSuffix != null">
                #{imageSuffix,jdbcType=VARCHAR},
            </if>
            <if test="spuId != null">
                #{spuId,jdbcType=INTEGER},
            </if>
            <if test="url != null">
                #{url,jdbcType=VARCHAR},
            </if>
            <if test="imgType != null">
                #{imgType,jdbcType=TINYINT},
            </if>
            <if test="status != null">
                #{status,jdbcType=TINYINT},
            </if>
            <if test="mainImg != null">
                #{mainImg,jdbcType=TINYINT},
            </if>
        </trim>
    </insert>

无论批量还是单个都可以调用具体看你调用的dao里面的批量方法还是单个这个sql是如果数据库没有这条数据就添加,否则就修改,通过主键id判断,如果不喜欢这中sql可以自己用常规的update方法

  <insert id="insertOrUpdate" parameterType="DBMap" useGeneratedKeys="true"
            keyProperty="id" keyColumn="id">
        insert into
        <include refid="tableName"></include>
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="imageName != null and imageName!=''">
                image_name,
            </if>
            <if test="imageSuffix != null and imageSuffix!=''">
                image_suffix,
            </if>
            <if test="spuId != null">
                spu_id,
            </if>
            <if test="url != null and url!=''">
                url,
            </if>
            <if test="imgType != null">
                img_type,
            </if>
            <if test="status != null">
                status,
            </if>
            <if test="mainImg != null">
                main_img,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id},
            </if>
            <if test="imageName != null">
                #{imageName,jdbcType=VARCHAR},
            </if>
            <if test="imageSuffix != null">
                #{imageSuffix,jdbcType=VARCHAR},
            </if>
            <if test="spuId != null">
                #{spuId,jdbcType=INTEGER},
            </if>
            <if test="url != null">
                #{url,jdbcType=VARCHAR},
            </if>
            <if test="imgType != null">
                #{imgType,jdbcType=TINYINT},
            </if>
            <if test="status != null">
                #{status,jdbcType=TINYINT},
            </if>
            <if test="mainImg != null">
                #{mainImg,jdbcType=TINYINT},
            </if>
        </trim>
        ON DUPLICATE KEY UPDATE
        <trim suffixOverrides=",">
            <if test="imageName != null and imageName!=''">
                image_name = #{imageName,jdbcType=VARCHAR},
            </if>
            <if test="imageSuffix != null and imageSuffix!=''">
                image_suffix = #{imageSuffix,jdbcType=VARCHAR},
            </if>
            <if test="spuId != null">
                spu_id = #{spuId,jdbcType=INTEGER},
            </if>
            <if test="url != null and url!=''">
                url=#{url,jdbcType=VARCHAR},
            </if>
            <if test="imgType != null">
                img_type=#{imgType,jdbcType=TINYINT},
            </if>
            <if test="status != null">
                status=#{status,jdbcType=TINYINT},
            </if>
            <if test="mainImg != null">
                main_img=#{mainImg,jdbcType=TINYINT},
            </if>
        </trim>
    </insert>
</mapper>

所有的接口层只需要定义xml,通过dao调用就可以直接获取数据库数据。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • MyBatis-Spring配置的讲解

    MyBatis-Spring配置简单了解 SqlSessionFactoryBean配置 在基本的 MyBatis 中,session 工厂可以使用 SqlSessionFactoryBuilder 来创建.而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来替代. 示例 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean&qu

  • spring、mybatis 配置方式详解(常用两种方式)

    在之前的文章中总结了三种方式,但是有两种是注解sql的,这种方式比较混乱所以大家不怎么使用,下面总结一下常用的两种总结方式: 一. 动态代理实现 不用写dao的实现类 这种方式比较简单,不用实现dao层,只需要定义接口就可以了,这里只是为了记录配置文件所以程序写的很简单: 1.整体结构图: 2.三个配置文件以及一个映射文件 (1).程序入口以及前端控制器配置 web.xml <?xml version="1.0" encoding="UTF-8"?> &

  • Spring整合Mybatis详细步骤

    一.基本介绍 所谓的Spring整合Mybatis其实说白了就是将mybatis的加载过程全权交给Spring托管,不再需要加载配置工具等一些操作,而具体的dao层操作依旧是使用mybatis去操作数据库. 1.1 mybatis使用步骤: 1.首先要写一个mybatis-config.xml核心配置文件,配置基本的环境支持:数据源.驱动.url.username.password- 2.然后编写mybatisUtil工具类,先以IO流的形式加载mybatis-config.xml资源Resou

  • SpringBoot多数据源配置详细教程(JdbcTemplate、mybatis)

    多数据源配置 首先是配置文件 这里采用yml配置文件,其他类型配置文件同理 我配置了两个数据源,一个名字叫ds1数据源,一个名字叫ds2数据源,如果你想配置更多的数据源,继续加就行了 spring: # 数据源配置 datasource: ds1: #数据源1 driver-class-name: com.mysql.jdbc.Driver # mysql的驱动你可以配置别的关系型数据库 url: jdbc:mysql://ip:3306/db1 #数据源地址 username: root #

  • mybatis spring配置SqlSessionTemplate的使用方式

    mybatis spring配置SqlSessionTemplate使用 1.application.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quo

  • 详解spring 配置的两种方式:JAVA配置和注解配置

    众所周知,spring自从3.0开始以后,就全面推荐使用配置的方式进行代码编写了,这种方式确实可以避免了之前一个项目里面一大堆XML的情况,毕竟XML的可读性实在不怎么样,而且一会写JAVA,一会写XML,确实还是蛮麻烦的 就目前来说spring的配置方式一般为两种:JAVA配置和注解配置.那么什么的是注解配置呢?什么是JAVA配置呢? //注解配置: @Service @Component @Repository @Controlle //JAVA配置 @Confirguration 相当于s

  • Spring Boot MyBatis 连接数据库配置示例

    最近比较忙,没来得及抽时间把MyBatis的集成发出来,其实mybatis官网在2015年11月底就已经发布了对SpringBoot集成的Release版本,示例代码:spring-boot_jb51.rar 前面对JPA和JDBC连接数据库做了说明,本文也是参考官方的代码做个总结. 先说个题外话,SpringBoot默认使用 org.apache.tomcat.jdbc.pool.DataSource 现在有个叫 HikariCP 的JDBC连接池组件,据说其性能比常用的 c3p0.tomca

  • MyBatis简介与配置MyBatis+Spring+MySql的方法

    1.1MyBatis简介 MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架.MyBatis 摒除了大部分的JDBC代码.手工设置参数和结果集重获.MyBatis 只使用简单的XML 和注解来配置和映射基本数据类型.Map 接口和POJO 到数据库记录.相对Hibernate和Apache OJB等"一站式"ORM解决方案而言,Mybatis 是一种"半自动化"的ORM实现. 需要使用的Jar包:mybatis-3.0.2.jar(mybatis

  • dubbo中zookeeper请求超时问题:mybatis+spring连接mysql8.0.15的配置

    这两天准备复习一下java,所以写一个采用dubbo的商场项目练练手,却卡第一个测试上,启动provider服务和Consumer服务,请求接口却始终报zookeeper请求超时错误(dubbo+zookeeper服务端重复调用三次),经过排查,我的问题是出在dao层与数据库连接的问题上(而且provider方还不报错,我也是R-此处省略一万字,其他都是正常的,如果你不是出在dao层连接数据库的问题,此文可能对你帮助不大).dao层采用mybatis+spring连接mysql数据库版本8.0.

  • Spring SpringMVC,Spring整合MyBatis 事务配置的详细流程

    整合思路 (1)SSM是什么? Spring,SpringMVC,Mybastis (2)思路 搭建整合的环境,初始化环境 搭建Spring环境,配置完成并测试 (service层) 再使用Spring整合MyBatis框架,并测试(Dao层) 最后使用Spring整合SpringMVC框架,并测试(web层) SSM搭建环境 (1)数据库创建ssm (2)创建maven工程 (3)git (创建.gitignore来过滤不用提交的文件) (4)依赖框架 (5)log4j.properties

  • ssm整合之Spring整合MyBatis框架配置事务的详细教程

    ssm整合之Spring整合MyBatis框架配置事务 1.在applicationContext.xml修改代码如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance

  • Mybatis之typeAlias配置的3种方式小结

    目录 Mybatis typeAlias配置 1.定义别名 2.扫描包方式 3.注解方式 springboot加载mybatis的typeAlias问题 为了清晰可见,直接贴代码 Mybatis typeAlias配置 1.定义别名 <typeAliases>      <typeAlias alias="User" type="cn.lxc.vo.User" /> </typeAliases> 2.扫描包方式 <typeA

  • Spring配置数据源的三种方式(小结)

    目录 一.前言 三.开发数据源的方式 方式1:手动输入 方式2:Properties配置文件 方式3:Spring配置数据源 四.总结 一.前言 今天学习了用spring配置Druid数据源的三种方式,整理了学习笔记,希望大家喜欢! 二.数据源的作用 数据源(连接池)是提高程序性能如出现的 事先实例化数据源,初始化部分连接资源 使用连接资源时从数据源中获取 使用完毕后将连接资源归还给数据源 常见的数据源:DBCP.C3P0.BoneCP.Druid等等,本文主要以Druid数据源为案例实现Spr

  • 详解Spring获取配置的三种方式

    目录 前言 Spring中获取配置的三种方式 通过@Value动态获取单个配置 通过@ConfigurationProperties+前缀方式批量获取 通过Environment动态获取单个配置 总结 前言 最近在写框架时遇到需要根据特定配置(可能不存在)加载 bean 的需求,所以就学习了下 Spring 中如何获取配置的几种方式. Spring 中获取配置的三种方式 通过 @Value 方式动态获取单个配置 通过 @ConfigurationProperties + 前缀方式批量获取配置 通

随机推荐