package com.example.scaffold.mapper; import com.example.scaffold.entity.User; import org.apache.ibatis.annotations.*; import org.apache.ibatis.cache.decorators.LruCache; import java.util.List; /** * User MyBatis Mapper - 演示 MyBatis 注解方式 * * 学习要点: * 1. @Mapper - 标记为 MyBatis Mapper 接口 * 2. @Select/@Insert/@Update/@Delete - SQL 注解 * 3. @Options - 额外选项(如返回自增ID) * 4. @ResultMap - 结果映射 * 5. @CacheNamespace - 二级缓存 */ @Mapper @CacheNamespace(implementation = LruCache.class, size = 1024) public interface UserMapper { /** * 查询所有用户 */ @Select("SELECT * FROM users ORDER BY created_at DESC") List findAll(); /** * 根据ID查询 - 使用一级缓存 */ @Select("SELECT * FROM users WHERE id = #{id}") User findById(@Param("id") Long id); /** * 根据用户名模糊查询 - 动态SQL演示 */ @Select("SELECT * FROM users WHERE username LIKE CONCAT('%', #{username}, '%')") List findByUsernameLike(@Param("username") String username); /** * 插入用户 - 返回自增ID */ @Insert("INSERT INTO users(username, email, phone, bio, active, created_at, updated_at) " + "VALUES(#{username}, #{email}, #{phone}, #{bio}, #{active}, NOW(), NOW())") @Options(useGeneratedKeys = true, keyProperty = "id") int insert(User user); /** * 更新用户 */ @Update("UPDATE users SET username=#{username}, email=#{email}, phone=#{phone}, " + "bio=#{bio}, active=#{active}, updated_at=NOW() WHERE id=#{id}") int update(User user); /** * 删除用户 */ @Delete("DELETE FROM users WHERE id = #{id}") int deleteById(@Param("id") Long id); /** * 统计用户数量 */ @Select("SELECT COUNT(*) FROM users") long count(); /** * 批量插入 - 演示脚本SQL */ @Insert("") int batchInsert(@Param("users") List users); }