实体类与Mapper

一、教学目标
创建User和News实体类,使用Lombok和MyBatis-Plus注解。
创建UserMapper和NewsMapper,继承BaseMapper。
测试基础查询。
二、核心知识点(简要)
@TableName:指定数据库表名。
@TableId:指定主键,IdType.AUTO表示自增。
@TableField(fill):自动填充。
@TableLogic:逻辑删除。
BaseMapper:提供通用CRUD方法。
三、操作步骤
本课次的操作是在上次课(课次23)的工程基础上继续操作。

  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接口口内容如下:

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 {
}
同样的操作创建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 {
}
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);
}

posted @ 2026-06-28 13:01  老熊二  阅读(2)  评论(0)    收藏  举报