赞
踩
完整代码下载地址:https://download.csdn.net/download/qq_37231511/12028858或
1.创建数据库mybatis_01,并建表user,插入一条数据,如图
2.创建springboot项目
点击next, 设置项目名称
点击next,选择需要用的框架,spring web、 mybatis、mysqlDriver
点击next,点击finish即创建成功,如图
3.整合MBG插件,自动生成实体类与mapper文件,MBG插件配置可见博文:https://blog.csdn.net/qq_37231511/article/details/103510314
4.配置application.properties
- #mysql
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_01?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
- spring.datasource.username=root
- spring.datasource.password=root
- #dao
- #与文件目录一致
- mybatis.type-aliases-package==com.xue.demo1.repository.dao
- mybatis.mapper-locations=classpath*:com/xue/demo1/repository/mapper/*.xml
5.在pom.xml中build中配置资源,因为mapper.xml文件没有放置到src-main-resources下面,是不会被maven build plugin给默认扫描到的
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- <filtering>true</filtering>
- </resource>
- </resources>
6. 创建controller包,并创建类UserController
- package com.xue.demo1.controller;
-
- import com.xue.demo1.entity.User;
- import com.xue.demo1.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- public class UserController {
-
- @Autowired
- private UserService userService;
- @RequestMapping("/user")
- public User getUser(){
- User user = userService.getUser(1);
-
- if (null != user){
- return user;
- }else {
-
- return null;
-
- }
-
-
- }
- }
7.创建service层创建接口UserService与接口实现类UserServiceImpl
UserService
- package com.xue.demo1.service;
-
- import com.xue.demo1.entity.User;
-
- public interface UserService {
-
- public User getUser(Integer id);
- }
UserServiceImpl
- package com.xue.demo1.service.impl;
-
- import com.xue.demo1.entity.User;
- import com.xue.demo1.repository.dao.UserMapper;
- import com.xue.demo1.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- @Service
- public class UserServiceImpl implements UserService {
-
- @Autowired
- private UserMapper userMapper;
- @Override
- public User getUser(Integer id) {
-
- User user = userMapper.selectByPrimaryKey(id);
-
- if(null != user){
- return user;
- }else {
- return null;
- }
- }
- }
8.至此代码编写完成,项目结构如图
9.运行项目,在浏览器输入localhost:8080/user,如图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。