第八节:SpringBoot集成MyBatis

来源:互联网 发布:ansys软件 编辑:程序博客网 时间:2024/06/06 02:23

pom.xml

<dependency>    <groupId>org.mybatis.spring.boot</groupId>    <artifactId>mybatis-spring-boot-starter</artifactId>    <version>1.3.1</version></dependency>
User实体类

package com.xiaowen.model;public class User {private Integer id;private String name;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age + "]";}}
UserMapper

package com.xiaowen.mapper;import org.apache.ibatis.annotations.Mapper;  import org.apache.ibatis.annotations.Select; import com.xiaowen.model.User;@Mapperpublic interface UserMaper {@Select("select * from t_user where age = #{age}")  User Select(int age); }

Controller

package com.xiaowen.controller;import com.xiaowen.mapper.UserMaper;import com.xiaowen.model.User;@RestControllerpublic class WebController {@Autowiredprivate UserMaper userMaper;@RequestMapping("/user")public User selectAge(int age){return userMaper.Select(age);}}

启动类

package com.xiaowen;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringBootDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringBootDemoApplication.class, args);}}
浏览器访问:http://localhost:8088/user?age=10


 Mybatis使用分页插件PageHelper

pom.xml配置

<dependency>      <groupId>com.github.pagehelper</groupId>      <artifactId>pagehelper</artifactId>      <version>4.1.0</version>  </dependency>  


package com.xiaowen.util;import java.util.Properties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.github.pagehelper.PageHelper;/** * 注册MyBatis分页插件PageHelper * @author xiaowen * */@Configurationpublic class MybatisConf {    @Beanpublic PageHelper pageHelper(){PageHelper pageHelper=new PageHelper();Properties p=new Properties();p.setProperty("offsetAsPageNum", "true");          p.setProperty("rowBoundsWithCount", "true");          p.setProperty("reasonable", "true");          pageHelper.setProperties(p);          return pageHelper;  }}

Controller

@RequestMapping("/user")public User selectAge(int age){//第一个参数是第几页;第二个参数是每页显示条数。PageHelper.startPage(1, 2);return userMaper.Select(age);}




原创粉丝点击