mybatis_CRUD实战

数据表:

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT ‘主键ID‘,
	name VARCHAR(30) NULL DEFAULT NULL COMMENT ‘姓名‘,
	age INT(11) NULL DEFAULT NULL COMMENT ‘年龄‘,
	email VARCHAR(50) NULL DEFAULT NULL COMMENT ‘邮箱‘,
	PRIMARY KEY (id)
);

实体类:

@AllArgsConstructor
@NoArgsConstructor
@Data
@Component
// 默认类名与表名一致,若不一致则使用注解标注表名()
// @TableName("user")
public class User {
    //类的所有属性都应该在数据库中
    @TableField(exist = false) // 在表中不存在
    private String username;
    @TableField(exist = false)
    private String password;

    private Long id;
    private String name;
    private Integer age;
    private String email;
}

mapper接口:

// 继承 BaseMapper 声明了众多基本增删改查方法
@Mapper
public interface UserMapper extends BaseMapper<User> {

}
  • BaseMapper:public interface BaseMapper extends Mapper

mybatis_CRUD实战

Service接口:

// 继承IService接口
// 声明了众多基本增删改查方法
public interface UserService extends IService<User> {

}
  • IService:public interface IService
    mybatis_CRUD实战

Service具体实现:

// 继承ServiceImpl类--->Iservice接口的众多方法的基本实现
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}
  • ServiceImpl:public class ServiceImpl<M extends BaseMapper, T> implements IService
    mybatis_CRUD实战

Controller

 @GetMapping("/dynamic_table")
    public String dynamic_table(Model model){
        
        // 表格从数据库获取数据
        List<User> list = userService.list();
        model.addAttribute("users",list);

        return "table/dynamic_table";
    }

dynamic_table表格

<table  class="display table table-bordered table-striped" id="dynamic-table">
        <thead>
        <tr>
            <th>#</th>
            <th>id</th>
            <th>name</th>
            <th>age</th>
            <th>email</th>
        </tr>
        </thead>
        <tbody>
        <!--users由model传入,user:users中的每一个元素,stats当前元素迭代状态-->
        <tr class="gradeX" th:each="user,stats:${users}">
            <td th:text = "${stats.count}">count</td>
            <td th:text = "${user.id}">id</td>
            <td th:text = "${user.name}">name</td>
            <td >[[${user.age}]]</td>
            <td >[[${user.email}]]</td>
        </tr>

        </tbody>
        </table>

mybatis_CRUD实战

上一篇:vuex


下一篇:自定义类加载器验证类加载机制