SpringBoot中 Mybatis 的xml映射文件配置

目录

1.依赖

2.示例代码

2.1不带resultMap标签示例

2.1带resultMap标签示例

3.resultMap标签不加的情况说明


1.依赖

在pom.xml文件中引入依赖

      
            org.mybatis.spring.boot
            mybatis-spring-boot-starter-test
            3.0.3
            test
        

2.示例代码

提示:在resource下创建文件mapper,用于存放xml配置文件

2.1不带resultMap标签示例

dao接口:

package com.example.springbootdemo.Mapper;

import com.example.springbootdemo.pojo.Student;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface StudentMapper{

    @Insert("insert into td_student(username, password, name, gender, age,create_time, update_time) "+
    "values(#{username},#{password},#{name},#{gender},#{age},#{createTime},#{updateTime})")
    void insert(Student student);

    void delete(List ids);

    void update(Student student);

    List list(String name, Short gender, LocalDate begin, LocalDate end);

    @Select("select * from td_student where  id = #{id}")
    Student getById(Integer id);

    @Select("select * from td_student where username=#{username}")
    Student getByUserName(String username);
}

对应的xml映射文件:




    
        update td_student
        
            
                username = #{username},
            
            
                password = #{password},
            
            
                gender = #{gender},
            
            
                age = #{age},
            
            
                name = #{name},
            
            
                update_time = #{updateTime},
            
        
        where id = #{id}
    

    
        delete from td_student where id in
        
            #{id}
        
    

    


当然还有这种加resultMap标签的情况:

2.1带resultMap标签示例

  
  
  
  
  
      
      
          
          
          
      
  
      
      
        INSERT INTO user (name, email) VALUES (#{name}, #{email})  
      
  
      
      
  
      
      
  
      
      
        UPDATE user SET name = #{name}, email = #{email} WHERE id = #{id}  
      
  
      
      
        DELETE FROM user WHERE id = #{id}  
      
  

3.resultMap标签不加的情况说明

这取决于你的具体需求。 在 MyBatis 中主要用于处理复杂的映射情况,比如联合查询、嵌套结果等。对于简单的 CRUD 操作,如果不涉及复杂的映射关系,通常不需要显式定义 

对于你的 User 实体类,如果它的属性名和数据库表中的列名完全一致,并且你不做特殊的映射处理(比如将数据库中的某个列映射到 Java 对象的另一个属性),那么你可以直接使用 resultType 来指定返回结果的类型,而不需要定义 

resultType 告诉 MyBatis 返回的结果应该被映射到 com.example.model.User 类型的对象上。MyBatis 会根据 SQL 查询返回的列名自动匹配 User 类中的属性名,并将相应的值赋给属性。

然而,如果你需要处理更复杂的场景,比如列名和属性名不匹配,或者需要映射到嵌套的对象,那么你就需要定义  来进行详细的映射配置。

你可能感兴趣的:(mybatis,xml,java,spring,boot)