zoukankan      html  css  js  c++  java
  • mybatis-basedao的实现

    package com.yangwei.shop.dao;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.ibatis.session.SqlSession;
    
    import com.yangwei.shop.entity.Pager;
    import com.yangwei.shop.entity.SystemContext;
    import com.yangwei.shop.util.MyBatisUtil;
    
    // 其中 Pager SystemContext 是自定义的分页类,前面mybatis有讲解 http://www.cnblogs.com/yangw/p/3315398.html
    /** * BaseDao 使用泛型 * 命令 :约定优于配置 */ public class BaseDao<T> { public void add(T obj){ SqlSession session=null; try { session = MyBatisUtil.createSession(); //约定 namespace值是该实体类的全路径,并且所有的添加都是add session.insert(obj.getClass().getName()+".add", obj); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ MyBatisUtil.closeSession(session); } } public void update(T obj){ SqlSession session=null; try { session = MyBatisUtil.createSession(); //约定 namespace值是该实体类的全路径,并且所有的更新都是update session.update(obj.getClass().getName()+".update", obj); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ MyBatisUtil.closeSession(session); } } public void delete(Class<T> clazz,int id){ SqlSession session=null; try { session = MyBatisUtil.createSession(); //约定 namespace值是该实体类的全路径,并且所有的删除都是delete session.delete(clazz.getName()+".delete", id); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ MyBatisUtil.closeSession(session); } } /** * 根据Id查找 */ public T load(Class<T> clazz,int id){ return this.load(clazz.getName()+"load", id); } /** * 根据指定的多个条件获取一条记录(最通用) */ public T load(String sqlId,Map<String,Object> params){ SqlSession session=null; T obj=null; try { session = MyBatisUtil.createSession(); //约定 namespace值是该实体类的全路径,并且所有的根据Id加载都是load obj=session.selectOne(sqlId, params); }finally{ MyBatisUtil.closeSession(session); } return obj; } /** * 根据指定的一个条件获取一条记录 */ public T load(String sqlId,Object param){ SqlSession session=null; T obj=null; try { session = MyBatisUtil.createSession(); //约定 namespace值是该实体类的全路径,并且所有的根据Id加载都是load obj=session.selectOne(sqlId, param); }finally{ MyBatisUtil.closeSession(session); } return obj; } /** * 有分页的查询 (默认是find) */ public Pager<T> find(Class<T> clazz,Map<String,Object> params){ return this.find(clazz.getName()+".find", params); } /** * 有分页的查询 (自行指定sqlId) */ public Pager<T> find(String sqlId,Map<String,Object> params){ int pageOffset=SystemContext.getPageOffset(); int pageSize=SystemContext.getPageSize(); String order=SystemContext.getOrder(); String sort=SystemContext.getSort(); Pager<T> pages=new Pager<T>(); SqlSession session=null; try { session = MyBatisUtil.createSession(); if(params==null) params=new HashMap<String,Object>(); params.put("pageOffset", pageOffset); params.put("pageSize", pageSize); params.put("order", order); params.put("sort", sort); //约定 namespace值是该实体类的全路径,并且所有的分页查询都是find List<T> lists=session.selectList(sqlId, params); pages.setDatas(lists); pages.setPageOffset(pageOffset); pages.setPageSize(pageSize); //获取当前条件下的所有记录数 //查询记录的命名是 XXX,那么约定记录条数命名是 XXX_count int count=session.selectOne(sqlId+"_count", params); pages.setTotalRecord(count); } finally{ MyBatisUtil.closeSession(session); } return pages; } /** * 不带分页的查询 (默认是list) */ public List<T> list(Class<T> clazz,Map<String,Object> params){ return this.list(clazz.getName()+".list", params); } /** * 不带分页的查询 ,自行指定sqlId * 排序依然带着 */ public List<T> list(String sqlId,Map<String,Object> params){ String order=SystemContext.getOrder(); String sort=SystemContext.getSort(); List<T> list=null; SqlSession session=null; try { session = MyBatisUtil.createSession(); if(params==null) params=new HashMap<String,Object>(); params.put("order", order); params.put("sort", sort); //约定 namespace值是该实体类的全路径,并且所有的分页查询都是find list=session.selectList(sqlId, params); } finally{ MyBatisUtil.closeSession(session); } return list; } }

    部分mapper.xml

    <mapper namespace="com.yangwei.shop.entity.Address">
        <insert id="add" parameterType="Address">
            insert into t_address (name,phone,postcode,user_id) value
                (#{name},#{phone},#{postcode},#{user.id})
        </insert>
        
        <update id="update" parameterType="Address">
            update t_address set 
                name=#{name},phone=#{phone},postcode=#{postcode} where id=#{id}
        </update>
        
        <delete id="delete" parameterType="int">
            delete from t_address where id=#{id}
        </delete>
        <select id="load" parameterType="int" resultType="Address">
            select * from t_address where id=#{id}
        </select>
        <select id="find" parameterType="map" resultType="Address">
            select * from t_address 
            <where>
                <if test="name!=null">
                    name like #{name} 
                 </if>
            </where>
             <if test="sort!=null">
                 order by ${sort}
                 <if test="order!=null">
                     ${order}
                 </if>
             </if>
            limit #{pageOffset},#{pageSize}
        </select>
        <select id="find_count" parameterType="map" resultType="int">
            select count(*) from t_address 
             <where>
                <if test="name!=null">
                    name like #{name} 
                 </if>
            </where>
            limit #{pageOffset},#{pageSize}
        </select>
        <select id="list" parameterType="map" resultType="Address">
            select * from t_address 
            <where>
                <if test="name!=null">
                    name like #{name} 
                 </if>
            </where>
             <if test="sort!=null">
                 order by ${sort}
                 <if test="order!=null">
                     ${order}
                 </if>
             </if>
        </select>
        <!-- 下面是一些特殊的情况,即不是我们能提前约定的-->
        <select id="list_by_name" >
        </select>
        <select id="list_by_name_count" >
        </select>
        

    再看看我们的dao变得如此之简洁

    package com.yangwei.shop.dao;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import com.yangwei.shop.entity.Address;
    import com.yangwei.shop.entity.Pager;
    
    public class AddressDao extends BaseDao<Address> implements IAddressDao {
    
    
        @Override
        public void addAddress(Address address, int userId) {
            //1,略 根据userId去t_user表加载User信息
            //2,将User设置到address中
            //3,调用父类方法 添加
            super.add(address);
        }
    
        @Override
        public void updateAddress(Address address) {
            super.update(address);
        }
    
        @Override
        public void deleteAddress(int id) { 
            super.delete(Address.class, id);
        }
    
        @Override
        public Address loadAddress(int id) {
            return super.load(Address.class, id);
        }
    
        @Override
        public Pager<Address> findAddress(String name) {
            
            Map<String, Object> params=new HashMap<String, Object>();
            if(name!=null && !"".equals(name)){
                params.put("name", "%"+name+"%");
            }
            return super.find(Address.class, params);
        }
        
    }
    ----------- 赠人玫瑰,手有余香     如果本文对您有所帮助,动动手指扫一扫哟   么么哒 -----------


    未经作者 https://www.cnblogs.com/xin1006/ 梦相随1006 同意,不得擅自转载本文,否则后果自负
  • 相关阅读:
    使用MobaXterm远程连接Ubuntu,启动Octave,界面不能正常显示
    ABP .Net Core 日志组件集成使用NLog
    ABP .Net Core Entity Framework迁移使用MySql数据库
    ABP前端使用阿里云angular2 UI框架NG-ZORRO分享
    阿里云 Angular 2 UI框架 NG-ZORRO介绍
    Visual Studio 2019 Window Form 本地打包发布猫腻
    VS Code + NWJS(Node-Webkit)0.14.7 + SQLite3 + Angular6 构建跨平台桌面应用
    ABP .Net Core 调用异步方法抛异常A second operation started on this context before a previous asynchronous operation completed
    ABP .Net Core To Json序列化配置
    .Net EF Core数据库使用SQL server 2008 R2分页报错How to avoid the “Incorrect syntax near 'OFFSET'. Invalid usage of the option NEXT in the FETCH statement.”
  • 原文地址:https://www.cnblogs.com/xin1006/p/3319290.html
Copyright © 2011-2022 走看看