SpringBoot 學習記錄(二): mybaits

繼續前篇學習,加入數據庫訪問層mybatis,這裏數據庫使用的是mysql

一,首先在原有的pom.xml中加入依賴:

	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.1.1</version>
	</dependency>
	
	<!-- mybatis分頁工具,需要版本1.1.1及以上 -->
	<dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>4.1.0</version>
    </dependency>
	
     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
這裏引入了mybaits分頁插件,PageHelper,是Github上以爲開發者提供的開源插件,使用很方便。

先看完整目錄結構:


二,在application.properties中配置數據源

#datasource
spring.datasource.url = jdbc:mysql://localhost:3306/yun?characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = centos
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
spring.datasource.sql-script-encoding=UTF-8
三,創建測試table
CREATE TABLE `demo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8
四,創建實體類Demo
package com.example.entity;

public class Demo {
	
	private long id;
	
	private String name;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
		

}
五,創建接口DemoMapper,這裏先採用註解方式實現,注意接口上不需要添加註解
package com.example.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.example.entity.Demo;

public interface DemoMapper {

    @Select("select * from demo where name = #{name}")
    public List<Demo> likeName(String name);
   
    @Select("select * from demo where id = #{id}")
    public Demo getById(long id);
}

六,創建DemoService + DemoServiceImpl

package com.example.service;

import java.util.List;

import com.example.entity.Demo;

public interface DemoService {
	
	public List<Demo> likeName(String name);
	
	public Demo getById(long id);

}

package com.example.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.example.entity.Demo;
import com.example.mapper.DemoMapper;
import com.example.service.DemoService;

@Service
public class DemoServiceImpl implements DemoService {
	
	@Resource
	private DemoMapper demoMapper;

	@Override
	public List<Demo> likeName(String name) {
		return demoMapper.likeName(name);
	}

	@Override
	public Demo getById(long id) {
		return demoMapper.getById(id);
	}

}

七,創建DemoController

package com.example.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.entity.Demo;
import com.example.service.DemoService;

@RestController
public class DemoController {

	@Resource
	private DemoService demoService;
	
	@RequestMapping(value="/demo/list",method=RequestMethod.GET)
	public List<Demo> list(String name){
		return demoService.likeName(name);
	}
	
}

八,啓動類DemoApplication添加註解,掃描mapper

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.*.mapper")//掃描該包下接口
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}
九,啓動測試

http://localhost:8088/spring-boot/demo/list?name=test

返回結果如下(預先在數據庫插入了4條數據,便於測試):

[
  {
    "id": 1,
    "name": "test"
  },
  {
    "id": 2,
    "name": "test"
  },
  {
    "id": 3,
    "name": "test"
  },
  {
    "id": 4,
    "name": "test"
  }
]
十,使用分頁插件,通過@Bean註解注入
package com.example.config;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.pagehelper.PageHelper;

@Configuration
public class PageHelperConfiguration {

	@Bean
    public 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;
    }
}
十一,DemoController新增分頁方法
@RequestMapping(value="/demo/page",method=RequestMethod.GET)
	public List<Demo> page(String name){
		PageHelper.startPage(1,2);
		return demoService.likeName(name);
	}
十二,訪問測試

http://localhost:8088/spring-boot/demo/page?name=test

返回結果如下:

[
  {
    "id": 1,
    "name": "test"
  },
  {
    "id": 2,
    "name": "test"
  }
]
=================================================================================================

以上是採用註解方式實現sql語句,下面採用常規的xml配置方式

十三,新增DemoMapper.xml

<?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="com.example.mapper.DemoMapper" >

  <resultMap id="BaseResultMap" type="com.example.entity.Demo" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
  </resultMap>
  
  <sql id="Base_Column_List" >
    id, name
  </sql>
  
  <select id="selectAll" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from demo
  </select>
  
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from demo
    where id = #{id,jdbcType=BIGINT}
  </select>
  
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from demo
    where id = #{id,jdbcType=BIGINT}
  </delete>
</mapper>
十四,接口中添加相應的方法

DemoMapper

int deleteByPrimaryKey(Long id);

    Demo selectByPrimaryKey(Long id);

	List<Demo> selectAll();
DemoService
int deleteByPrimaryKey(Long id);

    Demo selectByPrimaryKey(Long id);

	List<Demo> selectAll();
DemoServiceImpl
@Override
	public int deleteByPrimaryKey(Long id) {
		return demoMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Demo selectByPrimaryKey(Long id) {
		return demoMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Demo> selectAll() {
		return demoMapper.selectAll();
	}
十五,DemoController
	@RequestMapping(value="/demo/all",method=RequestMethod.GET)
	public List<Demo> all(){
		PageHelper.startPage(1,2);
		return demoService.selectAll();
	}
	
	@RequestMapping(value="/del",method=RequestMethod.DELETE)
	public int del(long id){
		return demoService.deleteByPrimaryKey(id);
	}
	
	@RequestMapping(value="/demo",method=RequestMethod.GET)
	public Demo get(long id){
		return demoService.selectByPrimaryKey(id);
	}

十六,方法都寫好了,最主要是在application.properties中註冊*.xml的目錄,添加如下配置:

#mapper.xml location
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
注意這裏配置的mybatis-config.xml主要是配置了別名,可以不用,這裏加上作爲補充知識點,方便以後使用

十七,測試,注意分頁插件依然生效,測試結果如下:



mybaits的使用到此結束,下篇繼續學習sping_boot爲我們提供的數據庫訪問層,SpringBoot 學習記錄(三): jpa








發佈了50 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章