[Spring] MyBatis操作数据库(基础)
warning:
这篇文章距离上次修改已过420天,其中的内容可能已经有所变动。
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(int id);
}
@Repository
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User getUserById(int id) {
return userMapper.getUserById(id);
}
}
// 使用UserService获取用户信息
public class UserServiceExample {
public static void main(String[] args) {
// 假设已经有Spring上下文
UserService userService = (UserService) ctx.getBean("userService");
User user = userService.getUserById(1);
System.out.println(user);
}
}这个代码示例展示了如何在Spring框架中使用MyBatis来操作数据库。首先定义了一个UserMapper接口,使用MyBatis的注解定义了一个查询用户信息的方法。然后定义了一个UserService类,它使用@Autowired注解自动注入UserMapper,并提供了一个公开的方法来调用UserMapper中的方法。最后,在UserServiceExample的main方法中,我们通过Spring的上下文获取UserService的实例,并调用getUserById方法来获取用户信息。
评论已关闭