栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis框架--2

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis框架--2

1.通过dao和映射文件的关联来完成操作---企业开发模式

思考: 我们之前使用SqlSession封装的一些方法可以完成crud操作,但是SqlSession封装的方法,传递的参数statement, 传递占位符的参数只能传递一个。而且他的方法名称都是固定。而真实在开发环境下我们不使用SqlSession封装的方法,而是习惯自己定义方法,自己调用自己的方法。

接口结合映射文件一起用。

1.1. 如何实现

(1)创建一个dao接口并定义自己需要的方法。

package com.wzh.dao;

import com.wzh.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;


public interface UserDao {
    
    public List findAll();
    
    public User findOne(int id);
    
    public int insert(User user);
    
    public int delete(int id);
    
    public int update(User user);
    
    public User findByNameAndPwd(@Param("username") String username,@Param("password") String password);
}

(2)创建映射文件





    
    
        insert into t_user values(null,#{username},#{password},#{relname})
    
    
        delete from t_user where id=#{id}
    
    
        update t_user set username=#{username},password=#{password},relname=#{relname} where id=#{id}
    
    

    
        select * from t_user where id=#{id}
    
    
        select stu_id stuId,stu_name stuName,stu_sex stuSex,stu_age stuAge,stu_salary stuSalary from student
    

 第二种: 使用resultMap完成列和属性之间的映射关系。



 

        select * from student where 1=1
            

            
                
                    and stu_name=#{stuName}
                
                
                    and stu_age=#{stuAge}
                
                
                    and stu_salay=#{stuSalary}
                
                
                    and stu_sex=0
                
            
        
    

    
        
        
        
        
        
    

 测试同上

 5.3.3.where标签

我们观察到上面的sql都加了 where 1=1 ,如果不使用where 1=1 那么你的动态sql可能会出错。 我们能不能不加where 1=1呢! 可以 那么我们就可以使用where标签,作用:可以自动为你添加where关键字,并且可以帮你去除第一个and |or



    
        
        
        
        
        
    
总结

1. 实际开发创建一个dao接口和映射文件。---namespace要和dao接口相同,id要和方法名相同。
2. 传递多个参数----@Param("名称") == xml #{名称}
3. 添加时需要获取递增的主键id.
4. 列名和属性名不一致。---别名    ===resultMap
5. 动态sql. 
     if
     choose
     where

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943770.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号