spring整合mybatis输出hello world
时间: 2023-03-21 22:00:52 浏览: 73
要在Spring中整合MyBatis并输出"Hello World",可以按照以下步骤:
1. 添加必要的依赖关系。在pom.xml中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2. 创建一个包含MyBatis配置的XML文件。例如,可以在src/main/resources目录下创建一个名为"mybatis-config.xml"的文件,并添加以下内容:
```xml
<configuration>
<settings>
<setting name="cacheEnabled" value="true" />
</settings>
<mappers>
<!-- 添加自己的mapper文件 -->
</mappers>
</configuration>
```
3. 创建一个Mapper接口和一个对应的Mapper XML文件,用于定义"Hello World"查询。例如,在src/main/resources/mapper目录下创建一个名为"HelloMapper.xml"的文件,并添加以下内容:
```xml
<?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.mapper.HelloMapper">
<select id="getHello" resultType="java.lang.String">
select 'Hello World'
</select>
</mapper>
```
在src/main/java目录下创建一个名为"HelloMapper.java"的接口,并添加以下内容:
```java
package com.example.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface HelloMapper {
@Select("select 'Hello World'")
String getHello();
}
```
4. 创建一个Service类来调用Mapper接口。在src/main/java目录下创建一个名为"HelloService.java"的类,并添加以下内容:
```java
package com.example.service;
import com.example.mapper.HelloMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
@Autowired
private HelloMapper helloMapper;
public String getHello() {
return helloMapper.getHello();
}
}
```
5. 创建一个Controller类来处理请求并调用Service类。在src/main/java目录下创建一个名为"HelloController.java"的类,并添加以下内容:
```java
package com.example.controller;
import com.example.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String hello() {
return helloService.getHello();
}
}
```
6. 运行应用程序并测试。运行应用程序并访问"http://localhost:8080/hello",应该会返回"Hello World"。