首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

MyBatis 入門實戰(一):從 XML 配置到註解開發的完整遷移指南

     編輯:Java 綜合教學

專案初始化

  1. Maven 依賴:
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.13</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.33</version>
    </dependency>
  2. 建表 message(id, command, description, comment)

核心配置檔 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <typeAliases>
    <package name="com.example.entity"/>
  </typeAliases>
  
  <environments default="dev">
    <environment id="dev">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  
  <mappers>
    <mapper resource="mapper/MessageMapper.xml"/>
  </mappers>
</configuration>

實體類與 Mapper 介面

// Message.java
@Data @NoArgsConstructor @AllArgsConstructor
public class Message {
    private Integer id;
    private String command;
    private String description;
    private String comment;
}

// MessageMapper.java
public interface MessageMapper {
    Message selectById(@Param("id") Integer id);
    List<Message> selectAll();
    @Insert("INSERT INTO message(command, description, comment) VALUES(#{command}, #{description}, #{comment})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Message msg);
    int update(Message msg);
    int deleteById(Integer id);
}

XML 映射檔 MessageMapper.xml(可選,支援混合模式)

<mapper namespace="com.example.mapper.MessageMapper">
  <resultMap id="msgMap" type="Message">
    <id property="id" column="id"/>
    <result property="command" column="command"/>
    <result property="description" column="description"/>
    <result property="comment" column="comment"/>
  </resultMap>
  
  <select id="selectById" resultMap="msgMap">
    SELECT * FROM message WHERE id = #{id}
  </select>
  
  <select id="selectAll" resultMap="msgMap">
    SELECT * FROM message
  </select>
</mapper>

啟動測試

public class App {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        
        try (SqlSession session = factory.openSession(true)) { // autoCommit=true
            MessageMapper mapper = session.getMapper(MessageMapper.class);
            
            // 查詢
            System.out.println(mapper.selectById(1));
            mapper.selectAll().forEach(System.out::println);
            
            // 新增
            Message msg = new Message(null, "CMD_001", "測試指令", "備註");
            mapper.insert(msg);
            System.out.println("生成 ID: " + msg.getId());
        }
    }
}

進階預告(下集)

  • 動態 SQL:<where>, <if>, <choose>, <foreach>
  • 關聯查詢:resultMap association/collection
  • 緩存機制:一級/二級緩存、Ehcache/Redis 整合
  • Spring Boot 整合:@MapperScan、分頁插件、多資料源
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved