SpringBoot++Mybatisplus+Thymeleaf模板

SpringBoot++Mybatisplus+Thymeleaf模板

一.创建SpringBoot项目

(1)idea直接选择Spring initializr可创建SpringBoot项目

在这里插入图片描述

(2)选择依赖

根据个人需求选择依赖,选择好后会直接在pom.xml中

在这里插入图片描述

mybatisplus依赖

		<!--mybatisplus-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.1.2</version>
		</dependency>

项目架构

在这里插入图片描述

(3)配置

​ application.yml

server:
  port: 5000
spring:
  datasource:                      #数据库连接池
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql:///homecrud?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

  devtools:           #热部署
         restart:
           enabled: true
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: LEGACYHTML5

二.代码编写

因为用了Mybatisplus代码生成器 根据数据库表反向生成pojo ,mapper,mapper.xml service,serviceimpl,controller,具体代码生成器使用见 mybatisplus篇

@TableName("real_eseate")
public class RealEseate extends Model<RealEseate> {

    private static final long serialVersionUID=1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @TableField("project_name")
    private String projectName;
    @TableField("address")
    private String address;
    @TableField("house_type")
    private String houseType;
    @TableField("area")
    private Integer area;
    @TableField("build_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private LocalDateTime buildTime;
    @TableField("user_id")
    private Long userId;
    //表示这个属性不会对应数据库中的列
    @TableField(exist = false)
    private User user;
}

mapper

public interface RealEseateMapper extends BaseMapper<RealEseate> {
    //高级分页查询
    IPage<RealEseate> queryPage(Page<RealEseate> page, @Param("query") Requery query);
}

因为涉及到分页,使用Mybatisplus必须配置一个分页bean

@EnableTransactionManagement
@Configuration
@MapperScan("cn.leilei.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // paginationInterceptor.setLimit(你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制);
        return paginationInterceptor;
    }
}

mapper.xml

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="cn.leilei.domain.RealEseate">
        <id column="id" property="id" />
        <result column="project_name" property="projectName" />
        <result column="address" property="address" />
        <result column="house_type" property="houseType" />
        <result column="area" property="area" />
        <result column="build_time" property="buildTime" />
        <result column="user_id" property="userId" />
         <!--关联对象属性-->
        <result column="uname" property="user.username"/>
        <result column="ucard" property="user.cardId"/>
    </resultMap>
    <!--查询条件-->
    <sql id="whereSql">
        <where>
            <if test="query.keywordName!=null and query.keywordName!=''">
                and
                ( u.username like concat('%',#{query.keywordName},'%')
                )
            </if>
            <if test="query.keywordCard!=null and query.keywordCard!=''">
                and
                (
                u.card_id like concat('%',#{query.keywordCard},'%')
                )
            </if>
        </where>
    </sql>
     <!--根据时间倒叙排列,分页 ,高级查询-->
    <select id="queryPage" resultMap="BaseResultMap">
        SELECT re.id,re.project_name,re.address,u.username uname,u.card_id ucard,re.house_type,re.area,re.build_time
        FROM real_eseate re LEFT JOIN user u ON re.user_id=u.id
        <include refid="whereSql"/> ORDER BY build_time DESC
    </select>

为考虑到前端框架分页所需数据的特殊性 封装一个分页对象类 (前端需要 total ,rows)

public class PageResult<T> {
    private Long total = 0L;   //每页条数

    private List<T> rows = new ArrayList<T>();   //每页数据

    public PageResult(Long total, List<T> rows) {
        this.total = total;
        this.rows = rows;
    }

    public PageResult() {

    }
    //get  set方法
}

service

public interface IRealEseateService extends IService<RealEseate> {
    PageResult<RealEseate> queryBypage(Requery requery);
}

serviceimpl

@Service
public class RealEseateServiceImpl extends ServiceImpl<RealEseateMapper, RealEseate> implements IRealEseateService {

    //关联用户分页查询
    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public PageResult<RealEseate> queryBypage(Requery query) {
        Page<RealEseate> page = new Page<>(query.getPage(),query.getRows());
        IPage<RealEseate> ip = baseMapper.queryPage(page, query);
        return new PageResult<>(ip.getTotal(),ip.getRecords());
    }
}

controller

@Controller
public class RealEseateController {
    @Autowired
    private IRealEseateService realEseateService;

    @RequestMapping("/index")
    public String index(org.springframework.ui.Model model, Requery requery) {
        PageResult<RealEseate> realEseatePageResult = realEseateService.queryBypage(requery);
        model.addAttribute("reals", realEseatePageResult.getRows());
        return "ye";
    }
    //添加的跳转
    @RequestMapping("/addIndex")
    public String addIndex(){
        return "add";
    }

    //添加
    @RequestMapping("/add")
    public String add(RealEseate user){
        realEseateService.save(user);
        return "redirect:/index";
    }

    //跳到修改页面
    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id, org.springframework.ui.Model model){
        RealEseate real = realEseateService.getById(id);
        model.addAttribute("real",real);
        return "update";
    }

    //修改
    @RequestMapping("/udpate")
    public String update(RealEseate user){
        realEseateService.updateById(user);
        return "redirect:/index";
    }

    //删除
    @RequestMapping("/delete")
    public String delete(Integer id){
        realEseateService.remove(new QueryWrapper<RealEseate>().eq("id", id));
        return "redirect:/index";
    }
}

前端页面(简单弄弄) html

ye.html

<body>

<table border="1" cellspacing="0">
    <tr>
        <td>id</td>
        <td>projectName</td>
        <td>address</td>
        <td>houseType</td>
        <a th:href="@{/addIndex}">新增</a>
    </tr>
    <tr th:each="real:${reals}">
        <td th:text="${real.id}"></td>
        <td th:text="${real.projectName}">projectName</td>
        <td th:text="${real.address}">address</td>
        <td th:text="${real.houseType}">houseType</td>
        <td>

            <a th:href="@{/toUpdate(id=${real.id})}">修改</a>
            <a th:href="@{/delete(id=${real.id})}">删除</a>

        </td>
    </tr>
</table>
</body>

add.html

<body>

<form th:action="@{/add}" method="post">
    <table>
        <tr>
            <td>productName</td>
            <td><input type="text" name="productName"></td>
        </tr>
        <tr>
            <td>address</td>
            <td><input type="text" name="address"></td>
        </tr>
        <tr>
            <td><input type="submit" value="add"></td>
        </tr>
    </table>
</form>

</body>

update.html

<body>
<form th:action="@{/udpate}" method="post">
    <table>
        <tr>
            <td><input type="hidden" name="id" th:value="${real.id}"></td>
        </tr>
        <tr>
            <td>projectName</td>
            <td><input type="text" name="projectName" th:value="${real.projectName}"></td>
        </tr>
        <tr>
            <td>address</td>
            <td><input type="text" name="address" th:value="${real.address}"></td>
        </tr>
        <tr>
            <td><input type="submit" value="udpate"></td>
        </tr>
    </table>
</form>
</body>

一个简单的页面以及crud功能就完成了
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值