package com.example.demo2022418;
//pojo
public class Article {
public Integer id;
public String title;
public String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package com.example.demo2022418;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
//mapper映射类
@Mapper
@Repository
public interface ArticleMapper {
//查询数据库操作
@Select("SELECT * FROM article WHERE id =#{id}")
public Article findById(Integer id);
//插入
@Insert("INSERT INTO article(id,title,content) values (#{id},#{title},#{content})")
public int insertArticle(Article article);
//更新
@Update("UPDATE article SET content=#{content} WHERE id =#{id}")
public int updateArticle(Article article);
//删除
@Delete("DELETE FROM article WHERE id=#{id}")
public int deleteArticle(Integer id);
}
#application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/teaching?serverTimezone=UTC
username: root
password: "001013" #0开头的密码需要加双引号
driver-class-name: com.mysql.cj.jdbc.Driver
package com.example.demo2022418;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
//测试
@SpringBootTest
class Demo2022418ApplicationTests {
@Test
void contextLoads() {
}
@Autowired
ArticleMapper articleMapper;
@Test
public void Mytest(){
//查询
Article article = articleMapper.findById(1);
System.out.println(article.getTitle());
//增加
Article article1 = new Article();
article1.setId(2);
article1.setTitle("2");
article1.setContent("2");
int i = articleMapper.insertArticle(article1);
//更改
Article article2 = new Article();
article2.setId(1);
article2.setContent("hello");
int i1 = articleMapper.updateArticle(article2);
//删除
int i2 = articleMapper.deleteArticle(2);
}
}
数据库表结构:
pom.xml相关依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>