SpringBoot(四):mybatis之通用mapper、分頁插件PageHelper

資料參考:MyBatis-Spring-Bootjava

一、集成Mybatis、通用Mapper和分頁插件PageHelper

DevTools 熱啓動配置會形成mybatis報錯,解決方案見MyBatis-Spring-Boot。示例取消了DevToolsmysql

  • pom.xml:jar引入
<!--mybatis-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		<!--mybatis之mapper插件-->
		<dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

		<!--mybatis之pagehelper插件-->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
  • application.properties:框架、插件配置
#mybatis
#數據庫實體對象位置
mybatis.type-aliases-package=com.ss.quickStart.domain
#mybatis中xml配置文件
mybatis.mapper-locations=classpath:mapper/*.xml

#mapper:https://github.com/abel533/Mapper
#mappers:指定基礎Mapper繼承接口,多個時逗號隔開
mapper.mappers=com.ss.quickStart.core.Mapper
#insert、update是否判斷字符串類型!='' 即 test="str != null"表達式內是否追加 and str != ''
mapper.not-empty=false
#主鍵生成策略:http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/3.Use.md 第3點
mapper.identity=MYSQL

#pagehelper:https://github.com/pagehelper/Mybatis-PageHelper
#指定數據庫分頁類型
pagehelper.helperDialect=mysql
#頁碼<=0 查詢第一頁,頁碼>=總頁數查詢最後一頁
pagehelper.reasonable=true
#支持經過 Mapper 接口參數來傳遞分頁參數:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
  • User.java:表實體對象,主鍵id設置爲自增
/**
 * Created by wsy on 2017/8/8.
 * 實體類註解:http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/3.Use.md:第2點
 */
@Table(name = "user")
public class User {
    @Id
    //@GeneratedValue(strategy = GenerationType.IDENTITY)
    //主鍵策略:http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/3.Use.md:第3點
    @GeneratedValue(generator = "JDBC")
    private Long id;

    @Column(name = "name")
    private String name;
    private Integer sex;

}
  • Mapper.java:自定義的通用Mapper
/**
 * 自定義Mapper
 * 關於Mapper詳解:http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/5.Mappers.md
 * @param <T>
 */
public interface Mapper<T> extends
        BaseMapper<T>,
        ConditionMapper<T>,
        IdsMapper<T>,
        InsertListMapper<T> {
}
  • UserMapper:User對象Dao層
public interface UserMapper extends Mapper<User> {

}
  • UserService:Service層代碼
@Service
public class UserService {
    private static final Logger  LOG = LoggerFactory.getLogger(UserService.class);
    @Resource
    private UserMapper userMapper;

    public User getById(long id){
        return userMapper.selectByPrimaryKey(id);
    }

    public Boolean add(User user){
        int count = userMapper.insert(user);
        LOG.info("新增用戶id=>{}",user.getId());
        return count==1?true:false;
    }

    public Boolean batchAdd(List<User> userList){
        int count = userMapper.insertList(userList);
        return true;
    }

    public List<User> findAll(){
        //return userMapper.selectAll();
        Condition condition = new Condition(User.class);
        condition.setOrderByClause("id DESC");
        return userMapper.selectByCondition(condition);
    }
}
  • UserController.java:controller層代碼
@RestController
public class UserController {
    @Autowired
    private PropertiesValues propertiesValues;

    @Resource
    private UserService userService;

    //取配置文件中author.name值,若沒有則賦值爲ss
    @Value("${author.name:ss}")
    private String name;

    @RequestMapping("getUser.do")
    public User getUser(){
        User user = new User();
        user.setName(propertiesValues.getUserName());
        user.setSex(1);
        System.out.println(MessageFormat.format("name=>{0}",name));
        return user;
    }

    @RequestMapping("user/getById.do")
    public User getById(Long id){
        return userService.getById(id);
    }

    @RequestMapping("user/add.do")
    public Boolean add(User user){
        return userService.add(user);
    }

    /**
     * 經過JSON方式解析入參:請求頭中content-type:application/json;Request Body:{"name": "AA","sex": 1}
     * localhost:8080/user/addByJSON.do?{"name": "AA","sex": 1}
     * @param user
     * @return
     */
    @RequestMapping("user/addByJSON.do")
    public Boolean addByJSON(@RequestBody User user){
        return userService.add(user);
    }

    /**
     * 批量添加用戶:
     * localhost:8080/user/batchAdd.do?userList[0].name=A&userList[0].sex=1&userList[1].name=B&userList[1].sex=0
     * @param userListDTO
     * @return
     */
    @RequestMapping("user/batchAdd.do")
    public Boolean batchAdd(UserListDTO userListDTO){
        return userService.batchAdd(userListDTO.getUserList());
    }

    @RequestMapping("/list")
    public PageInfo list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<User> list = userService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
  • QuickStartApplication.java:啓動類,增長@MapperScan,掃描對應Dao接口
@ServletComponentScan
@SpringBootApplication
@MapperScan(basePackages = "com.ss.quickStart.dao")
public class QuickStartApplication {

	public static void main(String[] args) {
		SpringApplication.run(QuickStartApplication.class, args);
	}
}
  • user.sql:user表建立sql
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `name` varchar(30) DEFAULT NULL,
  `sex` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

 

二、實例運行:分頁查詢

http://localhost:8080/list?page=5&size=5git

 

{
    "pageNum": 5,
    "pageSize": 5,
    "size": 2,
    "startRow": 21,
    "endRow": 22,
    "total": 22,
    "pages": 5,
    "list": [
        {
            "id": 2,
            "name": "s",
            "sex": 1
        },
        {
            "id": 1,
            "name": "w",
            "sex": 1
        }
    ],
    "prePage": 4,
    "nextPage": 0,
    "isFirstPage": false,
    "isLastPage": true,
    "hasPreviousPage": true,
    "hasNextPage": false,
    "navigatePages": 8,
    "navigatepageNums": [
        1,
        2,
        3,
        4,
        5
    ],
    "navigateFirstPage": 1,
    "navigateLastPage": 5,
    "firstPage": 1,
    "lastPage": 5
}

 

 

三、資料 參考

http://www.javashuo.com/article/p-qmkzuywb-gx.htmlgithub

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.mdspring

相關文章
相關標籤/搜索