使用Idea开始第一个Spingboot项目,整合Mybatis和Thymeleaf完成简单项目框架搭建。
整体项目结构
1、new--project,选择Spring Initializr
2、修改项目的信息,我这里使用默认
3、选择依赖,入门项目搭建,选择两个简单的就好。
web依赖
数据库驱动
4、项目搭建完成,然后再引入mybatis依赖和Thymeleaf依赖
org.springframework.boot
spring-boot-starter-thymeleaf
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
5、配置文件application.properties(我修改成了application.yml文件)
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: 123456
mybatis:
#mapper.xml配置,在resources文件夹下创建mapper文件夹
mapper-locations: classpath:mapper/*.xml
configuration:
#sql日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#别名配置
type-aliases-package: com.example.demo.entity
创建测试数据库test以及表user,然后创建controller、service、mapper。
数据库表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
INSERT INTO `user` VALUES (1, '刘备');
INSERT INTO `user` VALUES (2, '张飞');
INSERT INTO `user` VALUES (3, '许褚');
INSERT INTO `user` VALUES (4, '张辽');
INSERT INTO `user` VALUES (5, '刘备');
INSERT INTO `user` VALUES (6, '马岱');
DemoApplication.java
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
User.java
public class User implements Serializable {
private static final long serialVersionUID = 924072218502482859L;
private Integer id;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
UserController.java
@Controller
@RequestMapping("user")
public class UserController {
/**
* 服务对象
*/
@Resource
private UserService userService;
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@GetMapping("queryById")
public String selectOne(Integer id, Model model) {
User user = userService.queryById(id);
model.addAttribute("result",user);
return "index";
}
}
UserService,java
public interface UserService {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
User queryById(Integer id);
}
UserServiceImpl.java
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
@Override
public User queryById(Integer id) {
return this.userDao.queryById(id);
}
}
UserDao.java
public interface UserDao {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
User queryById(Integer id);
}
UserMapper.xml
index.html
首页
ID:
姓名: