- 导依赖
<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>
- 修改配置文件
#properties.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/teaching?serverTimezone=UTC
username: root
password: "001013" #0开头的密码需要加双引号
driver-class-name: com.mysql.cj.jdbc.Driver
#.xml的全局配置,注解开放不用
#mybatis:
# mapper-locations: classpath:mapper/*.xml #配置Mybatis的配置文件路径
# type-aliases-package: com.example.demo2022418.test425 #配置xml映射文件中指定的实体类别名路径
- 实体类
package com.example.demo2022418;
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;
}
}
- mapper映射类
package com.example.demo2022418;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
@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);
}
- 测试
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);
}
}
小节:
- 导依赖
- 修改配置文件
- 实体类
- 映射类
- 测试