1、创建meve## 标题n项目
File- > New -> Project -> Maven -> 。。。下一步 -> 等待Maven创建结束。
2、创建项目结构
3、更改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springbootdemo</groupId>
<artifactId>Springbootdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.8</version>
</parent>
<dependencies>
<dependency>
<!-- springboot的依赖,跟springmvc没关系,所以暂时也不用 spring-boot-starter-web -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<!-- mybatis相关依赖 -->
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<!-- mysql数据库依赖 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
</project>
4、创建相应文件
UserMapper.java
package com.strex.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
@Insert("INSERT INTO allwords.words (word,phoneticSymbol,Definitions) VALUES ('aaa','[ˈteilə]','n. 裁缝师'), ('bbb','[ʌnˈkɔnʃəs]','adj. 不省人事的;失去知觉的')")
void insertOne();
}
UserService.java
package com.strex.service;
import com.strex.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void test() {
userMapper.insertOne();
// throw new NullPointerException();
}
}
MyApplication.java
package com.strex;
import com.strex.service.UserService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
//添加springboot的注解
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(MyApplication.class);
UserService userService = applicationContext.getBean(UserService.class);
userService.test();
}
}
application.properties
#这个可以不配
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://11.22.33.44:3306/database?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username='***'
spring.datasource.password=***
5、运行
点击main左边的启动按钮运行
5、查看数据库是否插入成功
6、总结
springboot和spring的区别就是springboot只要能自动配置的部分,都会内部自动实现,简化了配置。