springboot学习:springboot+mybatis+MySQL+thymeleaf(二)

本节主要内容是springboot集成mybatis和MySQL,然后来访问数据库,完成从数据库获取数据。

1、准备工作。
(创建springboot项目可以参考:https://blog.csdn.net/weixin_42825721/article/details/81517224
新建一个springboot项目,然后在项目的pom.xml文件中引入如下依赖:



org.springframework.boot
spring-boot-starter-jdbc



org.springframework.boot
spring-boot-starter-web



mysql
mysql-connector-java
5.1.6


org.springframework.boot
spring-boot-starter-test



org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1



org.springframework.boot
spring-boot-starter-thymeleaf

2、在application.properties主配置文件中添加配置

数据库连接

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

设置mybatis的驼峰命名

mybatis.configuration.map-underscore-to-camel-case=true

thymeleaf配置

spring.thymeleaf.cache=false
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=html5
spring.thymeleaf.content=text/html

3、代码如下

1)、创建数据库(略),并且创建实体类
public class User {
private int id;
private String name;
private String password;
}
2)、创建mapper借口

public interface UserMapper {
@Insert(“insert into user values(#{name},#{password})”)
int addUser(User user);

@Select("select name,password from user")
List<User> selectAll();

@Select("select name,password from user where id=#{id}")
User queryById(int id);

}
3)、创建service和serviceImpl类
@Service
public class UserServiceImpl implements IUservice {
@Autowired
private UserMapper mapper;

@Override
public int addUser(User user) {
    return mapper.addUser(user);
}

@Override
public List<User> selectAll() {
    return mapper.selectAll();
}

@Override
public User queryById(int id) {
    return mapper.queryById(id);
}

}
4)、创建Controller测试类
@Controller
public class UserController {

@Autowired
private IUservice uservice;

@RequestMapping("/getAll")
@ResponseBody
public List<User> getAll() {

    return uservice.selectAll();
}

@RequestMapping("/getInfo")
public String getInfo(Map<String,Object> map) {
    List<User> info = uservice.selectAll();
    map.put("info",info);
    return "index";
}

}
5)、测试结果

6)、采用第二种,在页面获取数据
在上面的pom.xml中已经引入thymeleaf的依赖,然后在
application.propertiesies中配置文件。
创建index.html,改写html标签,这样可以使用th:*这种语法。

body部分如下:

namepassword


,然后测试结果如下:
这里写图片描述

4、可能出现的问题:

mysql驱动引起的jdbc4.MySQLSyntaxErrorException: Unknown character set: ‘utf8mb4’问题解决
出现这个是因为MySQL驱动问题,将MySQL的驱动改为5.1.6即可解决。版本高了也不行,低了也不行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值