实体类与Mapper
实体类与Mapper
一、核心知识点
- @TableName:指定数据库表名。
- @TableId:指定主键,
IdType.AUTO表示自增。 - @TableField(fill):自动填充。
- @TableLogic:逻辑删除。
- BaseMapper:提供通用CRUD方法。
二、操作步骤
1. 创建实体User:
- 右键
com.weitoutiao包名,创建entity.User类


-
类中内容如下:
package com.weitoutiao.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime; @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Integer id; private String username; private String password; private String role; private Integer newsCount; @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; }
2. 创建实体News:
-
同样的操作,再创建News类
-
News类中的内容如下:
package com.weitoutiao.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime; @Data @TableName("news") public class News { @TableId(type = IdType.AUTO) private Integer id; private Integer userId; private String title; private String content; private LocalDateTime publishTime; private Integer viewCount; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; @TableLogic private Integer deleted; }
3. 创建Mapper接口
- 右键
com.weitoutiao,创建一个名为mapper的软件包


- 右键
mapper文件夹,新建UserMapper接口


-
UserMapper接口内容如下:package com.weitoutiao.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.weitoutiao.entity.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { } -
同样的操作创建NewsMapper接口,内容如下:
package com.weitoutiao.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.weitoutiao.entity.News; import org.apache.ibatis.annotations.Mapper; @Mapper public interface NewsMapper extends BaseMapper<News> { }
4. 在启动类添加@MapperScan:
-
更改启动类
WeiTouTiaoSpringBootApplication中的内容如下:package com.weitoutiao; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.weitoutiao.mapper") public class WeiTouTiaoSpringBootApplication { public static void main(String[] args) { SpringApplication.run(WeiTouTiaoSpringBootApplication.class, args); } }
5. 编写测试类
- 右键test文件夹中的com.weitoutiao,创建一个测试类
testSelect


-
内容如下:
package com.weitoutiao; import com.weitoutiao.entity.User; import com.weitoutiao.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class UserMapperTest { @Autowired private UserMapper userMapper; @Test void testSelect() { List<User> users = userMapper.selectList(null);//查询出符合条件的所有数据,装进一个 List 集合里 users.forEach(System.out::println); } } -
点击运行
testSelect

- 运行结果,可以查到数据库中所有的user信息


浙公网安备 33010602011771号