springboot結合mybatis鏈接數據庫

1.所需springboot及數據庫相關依賴

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>test</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.2</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.45</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.9</version>
    </dependency>
複製代碼

*注意各依賴之間的版本兼容,不然容易出現報錯!java

2.編輯springboot配置文件 application.proper(yml),配置鏈接數據庫所須要的參數

spring:
  datasource:
   url: jdbc:mysql://localhost:3306/test
   username: 你的mysql帳號
   password: 你的mysql密碼
   driver-class-name: com.mysql.jdbc.Driver
複製代碼

3.編寫測試數據庫test及所需測試table

CREATE TABLE user(
  id INT NOT NULL UNIQUE auto_increment,
  name VARCHAR(64) NOT NULL,
  email VARCHAR(64) NOT NULL,
  PRIMARY KEY (id)
 )
複製代碼

4.編寫對應數據庫 user 表的對象 (mybatis ORM 特性)

public class User {
 private int id;
 private String name;
 private String email;

 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;
}

 public String getEmail() {
    return email;
}

 public void setEmail(String email) {
    this.email = email;
}
複製代碼

}mysql

5.編寫dao層(對數據庫進行CRUD)

@Mapper
 public interface UserDao {
   @Select("select id as id,name as name,email as email from user")
   List<User> findAllUser();

 }
複製代碼

6.編寫Service層 (調用dao層)

@Service
 public class UserService {

  @Autowired
  private UserDao userDao;

  public List<User> findAllUser(){
    return userDao.findAllUser();
 }
}
複製代碼

7.編寫controller層 (實現先後端交互,調用service層)

@RestController
 public class UserController {

  @Autowired
  private UserService userService;

  @RequestMapping("listall")
  public List<User> findAllUser01(){
    return userService.findAllUser();
 }
}
複製代碼

8.啓動springboot 應用

@SpringBootApplication
 public class App 
 {
  public static void main( String[] args )
  {
    SpringApplication.run(App.class,args);
  }
 }
複製代碼

9.訪問 http://localhost:8080/listall 便可驗證是否已經鏈接數據庫及操做數據庫

*springboot 默認服務端口爲8080web

*emmm 由於咱們沒有user表中加入數據 ,因此查看到數據爲空。 *注意 springboot 和數據庫相關版本的兼容性!!spring

相關文章
相關標籤/搜索