使用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映射操作。