使用MyBatis的注解方式进行SQL映射可以简化代码,不需要编写XML文件。以下是使用MyBatis的注解方式进行SQL映射的步骤:
public class User {
@Table(name = "user")
public class User {
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
// 省略getter和setter方法
}
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(Long id);
@Insert("INSERT INTO user (name) VALUES (#{name})")
void insertUser(User user);
@Update("UPDATE user SET name = #{name} WHERE id = #{id}")
void updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void deleteUser(Long id);
}
<mybatis:scan base-package="com.example.mapper"/>
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1L);
System.out.println(user.getName());
通过以上步骤,就可以使用MyBatis的注解方式进行SQL映射操作。