springboot+mybatis+mysql实例

springboot以配置少而备受javaee开发者的喜爱,并迅速成为最热门的开发框架。这里介绍springboot整合mybatis。

最终项目结构如下:

一、eclipse下新建maven工程,并引入依赖。

<parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.0.4.RELEASE</version>
  </parent>
  <dependencies>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
     <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.2</version>
     </dependency>
     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
     </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>springboot3</finalName>
        <plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
  </build>

二、编写Product.java

public class Product {
	private Integer id;
	private String name;
	private double price;
    // getter and setter 省略
}

ProductDao.java

package com.xxx.springboot.dao;
import java.util.List;
import com.xxx.springboot.entity.Product;
public interface ProductDao {
	List<Product> list();
	Product queryById(int id);
	int add(Product product);
	int update(Product product);
	int delete(int id);
}

配置ProductDao.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.xxx.springboot.dao.ProductDao">
    <select id="list" resultType="com.xxx.springboot.entity.Product">
        select id,name,price from product order by id desc;
    </select>
    <select id="queryById" resultType="com.xxx.springboot.entity.Product">
        select id,name,price from product where id = #{id}
    </select>
</mapper>

配置mybatis-config.xml

<?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>
    <settings>
        <setting name="useGeneratedKeys" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

编写ProductService.java接口文件

package com.xxx.springboot.service;
import java.util.List;
import com.xxx.springboot.entity.Product;
public interface ProductService {
	List<Product> list();
	Product queryById(int id);
	int add(Product product);
	int update(Product product);
	int delete(int id);
}

编写ProductServiceImpl.java

package com.xxx.springboot.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xxx.springboot.dao.ProductDao;
import com.xxx.springboot.entity.Product;
import com.xxx.springboot.service.ProductService;
@Service("productService")
public class ProductServiceImpl implements ProductService {
	
	@Autowired
	private ProductDao productDao;

	@Override
	public List<Product> list() {
		return productDao.list();
	}

	@Override
	public Product queryById(int id) {
		return productDao.queryById(id);
	}

	@Override
	public int add(Product product) {
		return productDao.add(product);
	}

	@Override
	public int update(Product product) {
		return productDao.update(product);
	}

	@Override
	public int delete(int id) {
		return productDao.delete(id);
	}

}

编写ProductController.java

package com.xxx.springboot.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.xxx.springboot.entity.Product;
import com.xxx.springboot.service.ProductService;
@RestController
@RequestMapping("/product")
public class ProductController {
	@Autowired
	private ProductService productService;
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Map<String, Object> list(){
		Map<String, Object> modelMap = new HashMap<String, Object>();
		List<Product> list = productService.list();
		modelMap.put("data", list);
		return modelMap;
	}
	
	@RequestMapping(value="/get/{id}",method=RequestMethod.GET)
	public Map<String, Object> get(@PathVariable("id")int id){
		Map<String, Object> modelMap = new HashMap<String, Object>();
		Product product = productService.queryById(id);
		modelMap.put("data", product);
		return modelMap;
	}
}

ProductDao.xml配置文件中目前只写了列表查询和按照ID查询接口的sql,这里也对应只实现list,get两个方法。

编写SpringBootStarter.java

package com.xxx.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
@MapperScan("com.xxx.springboot.dao")
public class SpringBootStarter extends SpringBootServletInitializer{
	public static void main(String[] args) {
		SpringApplication.run(SpringBootStarter.class, args);
	}
}

最后贴上application.yml配置文件截图:

准备数据:

CREATE TABLE `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `price` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

三、启动项目,分别访问http://localhost:8090/demo/product/list和http://localhost:8090/demo/product/get/3

查询id为3的product:

四、总结:

1、springboot以配置少著称,这里却引入了mybatis-config.xml。在mybatis-config.xml配置文件中配置了三个属性,分别是useGernatedKeys=true,用来指定如果是插入数据,采用自动生成主键的方式。useColumnLabel=true,用来指定可以使用列别名。mapperUnderscoreCamelCase=true,用来指定下划线转驼峰。比如数据库中create_date转换为实体类中属性createDate。这里如果不配置这些属性,mybatis-config.xml配置文件也可以不用。

2、这里只是在application.yml中配置了数据源信息,并没有指定数据源。也没有指定是否使用了连接池。

当通过浏览器访问:http://localhost:8090/demo/product/list的时候,我们在控制台看到如下信息:

这说明,默认采用的是Hikaricp数据源,而且使用了连接池。另外我们可以通过依赖库查看到,我们引入mybatis-spring-boot-starter时,自动加入了HikariCP-2.7.9.jar

这里还加入了一个mybatis-spring-boot-autoconfigurer-1.3.2.jar。这里面为我们默认配置了sqlSessionFactory,因此,我们也没有配置sqlSessionFactory就可以进行dao层接口的调用了。这比spring+mybatis整合确实少了很多配置。

3、启动类上面配置@MapperScan,感觉不是很好。我们可以在ProductDao上面增加注解@Mapper,这样就可以去掉SpringBootStarter启动类上面的@MapperScan注解了。

@Mapper
public interface ProductDao {
	List<Product> list();
	Product queryById(int id);
	int add(Product product);
	int update(Product product);
	int delete(int id);
}

-----------------------------------------------------------

@SpringBootApplication
//@MapperScan("com.xxx.springboot.dao")
public class SpringBootStarter extends SpringBootServletInitializer{
	public static void main(String[] args) {
		SpringApplication.run(SpringBootStarter.class, args);
	}
}

还可以直接在ProductDao.java接口类的方法上使用注解@Select、@Insert、@Update、@delete,这样连ProductDao.xml的映射文件也不需要了。

4、这里只是测试了查询方法,并没有测试新增,修改,删除,而这些方法在service层执行的时候,是需要配置事物的。这里需要注意。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值