mybatis整合springboot如何写注解的查询语句
时间: 2023-10-31 07:17:30 浏览: 79
在MyBatis整合Spring Boot中,我们可以使用注解来编写查询语句。下面是一个示例:
1. 首先,在你的实体类上使用注解来标识表名和字段名:
```java
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "age")
private Integer age;
// getters and setters
}
```
2. 在Mapper接口中使用注解来编写查询语句:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE username = #{username}")
User findByUsername(@Param("username") String username);
@Insert("INSERT INTO user(username, age) VALUES(#{username}, #{age})")
void save(User user);
@Update("UPDATE user SET age = #{age} WHERE username = #{username}")
void updateAgeByUsername(@Param("username") String username, @Param("age") Integer age);
@Delete("DELETE FROM user WHERE id = #{id}")
void deleteById(@Param("id") Long id);
}
```
3. 在Service层中使用Mapper接口进行数据操作:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findByUsername(String username) {
return userMapper.findByUsername(username);
}
public void save(User user) {
userMapper.save(user);
}
public void updateAgeByUsername(String username, Integer age) {
userMapper.updateAgeByUsername(username, age);
}
public void deleteById(Long id) {
userMapper.deleteById(id);
}
}
```
这样就可以使用注解来编写MyBatis的查询语句了。
阅读全文