以下是在 IntelliJ IDEA 中创建一个基于 Spring Cloud 的项目,使用 Spring Boot、MySQL 和 MyBatis 的步骤:
-
打开 IntelliJ IDEA,选择 Create New Project 选项。
-
在左侧菜单中选择 Spring Initializr,然后选择 Spring Cloud 作为项目类型。
-
在下一步中,选择 Spring Boot 版本,填写 Group 和 Artifact 名称,选择语言和包名。
-
在 Dependencies 中添加 MySQL 和 MyBatis 的依赖。点击 Add Dependencies,搜索 mysql 和 mybatis-spring-boot-starter,并勾选它们。
-
点击 Next,选择项目的名称和路径,完成项目的创建。
-
在 src/main/resources/application.properties 文件中,配置 MySQL 数据库的连接信息。例如:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
7.在 src/main/java/com/example/demo 目录下,创建一个新的 Java 类,作为项目的入口类。例如:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
8:在 src/main/java/com/example/demo 目录下,创建一个新的 Java 类,作为 MyBatis 的配置类。例如:
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisConfig {
}
9:在 src/main/java/com/example/demo/mapper 目录下,创建一个新的 Java 接口,作为 MyBatis 的 Mapper 接口。例如:
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
List<User> findAll();
}
10:在 src/main/java/com/example/demo/entity 目录下,创建一个新的 Java 类,作为 User 实体类。例如:
package com.example.demo.entity;
public class User {
private Long id;
private String username;
private String password;
public User() {
}
public User(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
11:在 src/main/resources/mapper 目录下,创建一个新的 XML 文件,作为 MyBatis 的 Mapper 映射文件。例如:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="userMap" type="com.example.demo.entity.User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</resultMap>
<select id="findAll" resultMap="userMap">
SELECT id, username, password FROM user
</select>
</mapper>
12:现在可以运行项目了。右键点击 DemoApplication.java 文件,选择 Run DemoApplication,或者使用快捷键 Shift + F10,启动项目。
13:在浏览器中访问 http://localhost:8080/users,可以看到返回的 JSON 数据,表示从 MySQL 数据库中查询出的 User 列表。