如何快速掌握mybatis基础入门技巧?
- 内容介绍
- 文章标签
- 相关推荐
本文共计411个文字,预计阅读时间需要2分钟。
配置和使用MyBatis查询用户信息:
sql配置MyBatis连接和Mapper:
1.在mybatis-config.xml中配置数据库连接信息。
2.创建UserMapper接口,定义selectUserById方法。
xml
javapublic interface UserMapper { User selectUserById(Integer id);}
2. 创建UserMapper.xml文件,编写selectUserById SQL语句。
xml SELECT * FROM userinfo WHERE id=#{id}
3. 在服务层调用Mapper接口的方法,获取用户信息。
javapublic class UserService { private final SqlSessionFactory sqlSessionFactory;
public UserService(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory=sqlSessionFactory; }
public User getUserById(Integer id) { try (SqlSession session=sqlSessionFactory.openSession()) { UserMapper mapper=session.getMapper(UserMapper.class); return mapper.selectUserById(id); } }}
4. 在控制器层调用服务层的方法,返回用户信息。
java@RestController@RequestMapping(/users)public class UserController { private final UserService userService;
public UserController(UserService userService) { this.userService=userService; }
@GetMapping(/{id}) public ResponseEntity getUserById(@PathVariable Integer id) { User user=userService.getUserById(id); return ResponseEntity.ok(user); }}
这样,你就可以通过访问http://localhost:8080/users/{id}来获取指定ID的用户信息了。
配置和使用mybatis
本文共计411个文字,预计阅读时间需要2分钟。
配置和使用MyBatis查询用户信息:
sql配置MyBatis连接和Mapper:
1.在mybatis-config.xml中配置数据库连接信息。
2.创建UserMapper接口,定义selectUserById方法。
xml
javapublic interface UserMapper { User selectUserById(Integer id);}
2. 创建UserMapper.xml文件,编写selectUserById SQL语句。
xml SELECT * FROM userinfo WHERE id=#{id}
3. 在服务层调用Mapper接口的方法,获取用户信息。
javapublic class UserService { private final SqlSessionFactory sqlSessionFactory;
public UserService(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory=sqlSessionFactory; }
public User getUserById(Integer id) { try (SqlSession session=sqlSessionFactory.openSession()) { UserMapper mapper=session.getMapper(UserMapper.class); return mapper.selectUserById(id); } }}
4. 在控制器层调用服务层的方法,返回用户信息。
java@RestController@RequestMapping(/users)public class UserController { private final UserService userService;
public UserController(UserService userService) { this.userService=userService; }
@GetMapping(/{id}) public ResponseEntity getUserById(@PathVariable Integer id) { User user=userService.getUserById(id); return ResponseEntity.ok(user); }}
这样,你就可以通过访问http://localhost:8080/users/{id}来获取指定ID的用户信息了。
配置和使用mybatis

