# 如何操作Mybatis/Mybatis-Plus
## 一、Mybatis基礎操作
### 1. 環境配置
```xml
<!-- pom.xml依賴 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- mybatis-config.xml -->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 數據庫連接配置 -->
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
// 接口定義
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User selectById(int id);
@Insert("INSERT INTO user(name) VALUES(#{name})")
int insert(User user);
}
<!-- 引入Mybatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
@Data
@TableName("sys_user") // 指定表名
public class User {
@TableId(type = IdType.AUTO) // 主鍵策略
private Long id;
private String username;
}
// 繼承IService接口
public interface UserService extends IService<User> {}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {}
// QueryWrapper示例
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("username", "admin")
.between("age", 20, 30)
.orderByDesc("create_time");
List<User> users = userMapper.selectList(wrapper);
特性 | Mybatis | Mybatis-Plus |
---|---|---|
CRUD實現 | 需手動編寫SQL | 內置通用Mapper |
分頁 | 需插件 | 原生支持 |
代碼生成 | 無 | 提供代碼生成器 |
樂觀鎖 | 需手動實現 | @Version注解支持 |
提示:Mybatis-Plus是對Mybatis的增強而非替代,二者可混合使用 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。