-->SpringBoot企业级开发精讲系列教程
本章带大家使用springboot + mybaits整合,实现一个简单的登录实例
准备:
1.安装mysql
2.创建springboot数据库
3.创建s_user表
DROP TABLE IF EXISTS `s_user`;
CREATE TABLE `s_user` (
`_id` int(11) NOT NULL AUTO_INCREMENT,
`nickname` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
`create_time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
这里创建用户表user,加前戳s_其意义是区分系统表和具体事务表,在此项目中使用到的前戳有:
前戳 | 全称 | 描述 |
---|---|---|
s_ | system | 系统表前戳 |
b_ | business | 事务表前戳 |
1.创建User数据库表映射实体类
@Data
public class User {
private int _id;
private String nickname;
private String password;
private long create_time;
}
注意字段名和变量名保持一致
2.创建UserDao类
@Mapper
public interface UserDao {
User login(@Param("nickname") String nickname, @Param("password")String password);
}
3.创建service
@Slf4j
@Service
public class UserService {
@Autowired
private UserDao mUserDao;
public LoginRPTO login(LoginRQTO login){
User user = mUserDao.login(login.getNickname(),login.getPassword());
if(user == null){
return null;
}
LoginRPTO rpto = new LoginRPTO();
rpto.setUser_id(user.get_id());
rpto.setNickname(login.getNickname());
return rpto;
}
}
4.修改UserController
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService mUserService;
@ResponseBody
@RequestMapping(value = "/login",method = RequestMethod.POST)
public RPTO login(@RequestBody @Valid LoginRQTO login) {
LoginRPTO rpto = mUserService.login(login);
if(rpto == null){
return new RPTO<>("用户名密码错误");
}
return new RPTO<>(ActionCode.SUCCESS,rpto);
}
}
5.在resource目录下创建mapper目录,并新建UserMapper.xml
6.修改application.properties
server.port=8080
#日志配置
logging.level.root=warn
logging.level.com.fcibook.springboot=DEBUG
#springframework.web日志以DEBUG级别输出
logging.level.org.springframework.web=warn
#hibernate日志以ERROR级别输出
logging.level.org.hibernate=warn
logging.file=/logs/my.log
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
#数据库配置
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
#配置.xml文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置模型路径
mybatis.type-aliases-package=com.fcibook.springboot.dao
7.运行,测试
在数据库中,手动添加一条记录
然后打开网址
http://localhost:8080/login.html
登录测试成功!
但是值得一提的是mybatis有多种方法来操作数据库,我们访问mybatis官网
http://www.mybatis.org/mybatis-3/zh/getting-started.html
看到如下文档解释:
----------------------------------------------------------------------
源码下载