聲明:原創(chuàng)文章,轉載請注明出處。http://www.itdecent.cn/p/43ade838dcc0
一、概述
上一節(jié)中,我們分享了SpringBoot快速建立一個web項目,本節(jié)中我們將在web項目中引入數(shù)據(jù)庫相關的操作。即SpringBoot通過整合MyBatis訪問數(shù)據(jù)庫。
二、快速整合Mybatis
1、修改pom.xml,添加依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
這里仍然需要springboot的parent,同時需要添加mysql和mybatis的相關依賴。
2、添加數(shù)據(jù)庫相關配置
在resources目錄下,添加application.properties文件。具體內容如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=user
spring.datasource.password=gJV88HBxvgiQdL8Z6AAFFSKTEkgfdsgfsg==
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3、添加其他代碼
這里我們需要創(chuàng)建4個類,第一個是SpringBoot的啟動類,和上一節(jié)的相同。
- 創(chuàng)建SpringBoot啟動類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(MovieRecommApplication.class, args);
}
}
- 創(chuàng)建一個Model類
public class User {
private int id;
private String name;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public String toString() {
return "User{id=" + id + ", name='" + name + '\'' + '}';
}
}
這里需要注意的是,屬性的名字要和數(shù)據(jù)庫中的名字保持一致。
- 創(chuàng)建一個Mapper類
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user_table WHERE id = #{id}")
User getUserById(@Param("id") int id);
}
- 創(chuàng)建一個Controller類
@RestController
@EnableAutoConfiguration
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String user() {
User user = userMapper.getUserById(1);
return user.toString();
}
}
通過這個Controller進行查詢,然后將數(shù)據(jù)返回。
4、運行
通過瀏覽器訪問http://127.0.0.1:8080/user,即可以看到結果。