1、访问:
https://start.spring.io/
eclipse --> import :
2、pom.xml 中 加入Web依赖
org.springframework.boot spring-boot-starter-web3、创建controller
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return “Hello , This is you first SpringBoot Web Project !”;
}
}
4、启动运行:
@SpringBootApplication
public class DemoYangyApplication {
public static void main(String[] args) {
SpringApplication.run(DemoYangyApplication.class, args);
}
}
5、访问:
http://localhost:8080/hello
6、spring 中使用 mysql
application.properties 加入配置:
##\u6570\u636E\u5E93\u5730\u5740
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##\u6570\u636E\u5E93\u7528\u6237\u540D
spring.datasource.username=root
##\u6570\u636E\u5E93\u5BC6\u7801
spring.datasource.password=root
##\u6570\u636E\u5E93\u9A71\u52A8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
pom.xml中加入:
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
7、使用JDBC操作数据库
pom.xml: 增加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
8、Controller 中测试jdbcTemplate
@RestController
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate;
//http://localhost:8080/createTable
@GetMapping("createTable")
public String createTable(){
String sql =
"CREATE TABLE `user` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `user_name` varchar(255) NOT NULL,\n" +
" `user_password` varchar(255) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;";
jdbcTemplate.execute(sql);
return "创建User表成功";
}
//http://localhost:8080/saveUserSql
@GetMapping("saveUserSql")
public String saveUserSql(){
String sql = "INSERT INTO USER (USER_NAME,USER_PASSWORD) VALUES ('dalaoyang','123')";
int rows= jdbcTemplate.update(sql);
return "执行成功,影响"+rows+"行";
}
9、使用MyBatis操作数据库
MyBatis依赖配置
pom.xml 文件中增加:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>