美文网首页
SpringBoot MyBatis + 页面渲染

SpringBoot MyBatis + 页面渲染

作者: BitterOutsider | 来源:发表于2021-01-07 14:49 被阅读0次

在 Spring Boot 中使用 MyBatis

我们用一个获取排行榜的小应用作为例子。

依赖与配置

  1. 引入所依赖的类库,在 MyBatis 的官网可以找到。接着引入 h2 数据库所需的类库。
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>
  1. 配置 datasource
    对于 Spring Boot 来说,需要进行一些配置,将 application.properties 放在 src/main/resources 下。在官方文档中可以找到。
spring.datasource.url=jdbc:h2:file:./target/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=org.h2.Driver
  1. 配置 flyway 自动化迁移插件以及 sql 初始化语句
    在 src/main/resources/db/migration 下创建 V1__CreateTables.sql 用于初始化数据库(一定注意这里是两个下划线,踩过坑)。运行 mvn flyway:migrate 初始化数据库。这里不赘述细节。
create table user
(
    id bigint primary key auto_increment,
    name varchar(100)
)

create table match
(
    id bigint primary ket auto_increment,
    user_id bigint,
    score int
)

insert into user (id, name) values (1, 'AAA');
insert into user (id, name) values (2, 'BBB');
insert into user (id, name) values (3, 'CCC');

insert into match (id, user_id, score) values (1, 1, 1000);
insert into match (id, user_id, score) values (2, 1, 2000);
insert into match (id, user_id, score) values (3, 2, 500);
insert into match (id, user_id, score) values (4, 3, 300);
<plugin>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-maven-plugin</artifactId>
    <version>7.4.0</version>
    <configuration>
        <url>jdbc:h2:file:./target/test</url>
        <user>root</user>
        <password>root</password>
    </configuration>
</plugin>
  1. 配置 MyBatis
    在 application.properties 中加入
mybatis.config-location = classpath:db/mybatis/config.xml

在 db/mybatis/config.xml 中写入 mybatis 配置,同样我们在官网抄。值得注意的是我们在Spring datasource中已经配置好了环境,所以mybatis中的<environments></environments> 环境配置部分可以全都不要。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
            <mapper resource="db/mybatis/MyMapper.xml"/>
    </mappers>
</configuration>

两种方式使用 MyBatis

  1. 注解
    注意这里是接口不是类
@Mapper
public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") Integer id);
}

在config.xml 中加入mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <mapper resource="db/mybatis/MyMapper.xml"/>
        <mapper class="hello.dao.UserMapper"/>
    </mappers>
</configuration>
@RestController
public class HelloController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/")
    @ResponseBody
    public Object index() {
        return userMapper.getUserById(1);
    }
}
  1. xml
    我们使用 xml 写好 mapper。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="MyMapper">
    <select id="selectRank" resultMap="rankItem">
        select user.id, user.name as name, total_score as score
        from
        (select user_id, sum(score) as total_score, from match group by user_id) m
        join user
        on m.user_id = user.id
    </select>
    <resultMap id="rankItem" type="hello.entity.RankItem">
        <result property="score" column="score"/>
        <association property="user" javaType="hello.entity.User">
            <result property="name" column="name"/>
            <result property="id" column="id"/>
        </association>
    </resultMap>
</mapper>

如何让 Spring 容器知道一个类是一个Bean(可以被注入,需要被注入等),一种简单的方法就是在 class 上使用注解 @Service 或者 @Component。换一句话说只有声明了 @Service,Bean才能被识别或是自动 Autowired。还有一种较为复杂的声明 Bean 的方式,这里先不展开。现在问题来了,我们知道在使用MyBatis时,我们需要一个 SqlSessionFactory 和一个 SqlSession 才能完成一系列 select 操作。但是在 Spring Boot 中这些东西从哪来呢?既然我们在使用 Spring,那么所有的依赖都需要 Spring 自动帮我们完成,这个时候非常简单。我们只需要自动注入一个 SqlSession 就好了,Spring 会自动帮你完成依赖的装配和注入,然后就直接用它吧。

@Service
public class RankDao {
    @Autowired
    private SqlSession sqlSession;

    public List<RankItem> getRank() {
        return sqlSession.selectList("MyMapper.selectRank");
    }
}
@Service
public class RankService {
    @Autowired
    private RankDao rankDao;

    public List<RankItem> getRank() {
        return rankDao.getRank();
    }
}
@RestController
public class HelloController {
    @Autowired
    private RankService rankService;

    @RequestMapping("/")
    @ResponseBody
    public Object index() {
        return rankService.getRank();
    }
}

页面渲染

后端渲染

我们考虑使用模板引擎,模板引擎有 freemaker、jsp、velocity 。目前最流行的模板引擎是 Freemaker。与 MyBatis 相似,Freemaker 也有一个 spring-boot-starter-freemaker 的依赖类库。我们需要在 resources/templates 目录下创建 .ftlh 格式的模板文件,还需要排行榜的数据。我们称这种响应 HTTP 的方式叫做 Model And View。有如下的写法:

// html.ftlh
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>排行榜</title>
</head>
<body>
    <table>
        <tr>
            <th>排名</th>
         <th>名字</th>
         <th>分数</th>
        </tr>
        <tr>
            <td>${index}</td>
            <td>${name}</td>
            <td>${score}</td>
        </tr>
    </table>
</body>
</html>
@RestController
public class HelloController {
    @RequestMapping("/")
    public ModelAndView index() {
        Map<String, Object> model = new HashMap<>();
        model.put("index", 1);
        model.put("name", "Zhang San");
        model.put("score", 1000);
        return new ModelAndView("index", model);
    }
}

根据 Freemaker 的语法,把所有数据填上去就可以了。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>排行榜</title>
</head>
<body>
    <table>
        <tr>
           <th>排名</th>
           <th>名字</th>
           <th>分数</th>
        </tr>
        <#list items as item>
           <tr>
               <td>${item?index+1}</td>
               <td>${item.user.name}</td>
               <td>${item.score}</td>
           </tr>
        </#list>
    </table>
</body>
</html>
@RestController
public class HelloController {
    @Autowired
    private RankService rankService;

    @RequestMapping("/")
    public ModelAndView index() {
        List<RankItem> items = rankService.getRank();
        Map<String, List<RankItem>> model = new HashMap<>();
        model.put("items", items);
        return new ModelAndView("index", model);
    }
}

前段渲染

使用 JS 和 JSON 异步请求进行前端渲染。在 resources/static 下创建 index.html。Spring 规定在resource/static 目录下的文件可以直接访问。前端只需要用 ajax 访问某个接口获取数据,前端使用 js 动态的把数据加载到 html 上。

相关文章

网友评论

      本文标题:SpringBoot MyBatis + 页面渲染

      本文链接:https://www.haomeiwen.com/subject/jsqboktx.html