用mybatis的注解方式写
时间: 2023-08-04 20:36:29 浏览: 70
好的,这里给您展示一下使用MyBatis注解方式编写DAO和Mapper的示例代码:
**1. DAO层代码:**
```java
public interface UserDao {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(int id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int addUser(User user);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
int updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteUser(int id);
}
```
**2. Mapper层代码:**
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(@Param("id") int id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int addUser(User user);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
int updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteUser(@Param("id") int id);
}
```
以上代码中,使用了MyBatis注解方式编写了DAO接口和Mapper接口。其中,
- @Select:查询操作;
- @Insert:新增操作;
- @Update:修改操作;
- @Delete:删除操作;
- @Options:设置自动生成主键时的属性。
需要注意的是,使用注解方式时,需要在启动类上添加@MapperScan注解,指定Mapper接口所在的包路径,如下所示:
```java
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
这样就可以使用MyBatis的注解方式编写DAO和Mapper了。
阅读全文