有时候做方案,需要模拟一些业务上的一些场景来验证方案的可行性,基本上每次都是到处百度如何集成springboot+mybatis+thymeleaf这些东西的集成平时基本上一年也用不了一次,虽然比较简单,奈何我真得记不住详细的每一步,因此每次都是从零开始,我一直在想,把时间浪费在这种重复的事情是没有意义的,所以这篇文章记录一下,以后再也不到处百度来接拼凑了。
springboot中集在mybatis和thymeleaf,简单实现一下新增和查询功能,后续有需要再往上补。
jdk版本:1.8
开发工具:Intellij iDEA 2020.1
springboot:2.3.9.RELEASE
主要引入了springboot、thymeleaf、mybais、mysql、jdbc以及热部署和lombda相关的依赖;
org.springframework.boot spring-boot-starter
org.springframework.boot spring-boot-starter-web
org.springframework.boot spring-boot-starter-test test
org.springframework.boot spring-boot-starter-thymeleaf
ognl ognl 3.1.26
org.projectlombok lombok
org.springframework.boot spring-boot-devtools true
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4
org.springframework.boot spring-boot-starter-jdbc
mysql mysql-connector-java
配置文件这里新增了三处配置,分别是thymeleaf、数据库连接、mybatis;
#thymeleaf配置
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=utf-8
#数据库连接配置
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3307/happy_home?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
#mybatis配置
mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
1、resources/static目录下,新增静态文件index.html;
Title
2、resources/templates目录上,新增home.html文件;
主页
ID:
登陆名:
姓名:
性别:
手机号码:
身份证号:
地址:
门牌号:
后端代码
1、PersonController.java
@Controller
@RequestMapping("/person")
public class PersonController {@Autowiredprivate IPersonService personService;@PostMapping("/registe")public String registe(Person person, Model model) {Integer id = this.personService.registe(person);model.addAttribute("id", id);return "home";}@GetMapping("/{id}")@ResponseBodypublic Person getPerson(@PathVariable("id") Integer id) {Person person = this.personService.get(id);return person;}
}
2、IPersonService.java
public interface IPersonService {Integer registe(Person person);Person get(Integer id);
}
3、PersonServiceImpl.java
@Service
public class PersonServiceImpl implements IPersonService {@Autowiredprivate PersonDao personDao;@Overridepublic Integer registe(Person person) {this.personDao.insert(person);return person.getId();}@Overridepublic Person get(Integer id) {Person person=personDao.selectById(id);return person;}
}
4、PersonDao.java
@Mapper
public interface PersonDao {Integer insert(Person person);Person selectById(Integer id);
}
5、PersonMapper.xml
insert into sys_person(user_name, login_no, phone_number, sex, ID_card, address, house_number)values (#{userName}, #{loginNo}, #{phoneNumber}, #{sex}, #{IDCard}, #{address}, #{houseNumber})
6、Person.java
@Slf4j
@Data
public class Person {private Integer id;private String userName;private String loginNo;private String phoneNumber;private String sex;private String IDCard;private String address;private String houseNumber;
}