一.建立springboot項目
建立一個springboot項目并引入資料庫和mybatis相關依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</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>2.1.4</version>
</dependency>
二.配置資料源datasource和mybais
這裡采用yaml方式配置資料源,引入yaml依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
在resource目錄下建立application.yml配置檔案并添加datasource配置
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/testdatabase
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.example.aliases
(資料庫名字改成自己的資料庫名字,密碼和使用者名也是)
mybatis的type-aliase-package屬性表示對應資料庫表的實體類所在包,跟表對應的實體類建在哪個包就配哪個。
三.編寫mapper接口(基于注解)用于執行sql語句
package com.example.mapper;
import com.example.aliases.UserAliase;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface UserMapper {
@Select("select*from user")
List<UserAliase> getAll();
@Select("select * from user where username=#{username}")
UserAliase getByUsername(String username);
@Insert("insert into user(username,password) valuses(#{username},#{password})")
void insert(UserAliase user);
@Delete("delete from user where username=#{username}")
void delete(String username);
@Update("update user set password=#{password} where username=#{username}")
void changePassword(String username,String password);
}
(UserAliase是我寫的資料庫表對應實體類的類名,這裡也要改成自己的)
四.在主類上添加MapperScan注解
@SpringBootApplication
@MapperScan("com.example.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
注:@MapperScan的值寫mapper接口所在包
最後在要調用資料庫操作的類中自動注入Mapper接口就可以使用了。
@Controller
public class MyHandler {
@Autowired
UserMapper usermapper;
@ResponseBody
@RequestMapping("getAll")
public List<UserAliase> getAll(){
return usermapper.getAll();
}
@ResponseBody
@RequestMapping("loginCheck")
public String getById(@RequestParam("username") String username, @RequestParam("password") String password){
UserAliase user=usermapper.getByUsername(username);
if(user!=null){
if(user.getPassword().equals(password))
return "登入成功";
else return "密碼錯誤";
}
else return "該使用者不存在";
}
寫個登入頁面測試一下
送出
(第一次寫部落格,有什麼問題歡迎指出)