学习springboot第3步,Mybatis操作数据库2

     Springboot操作数据库用Mybatis框架,好像有点意犹未尽,是不是可以和Hibernate + JPA 的方式一样,简单一点,不要什么XML文件,嗯,是的,可以不需要。就是接口类的写法稍微有点不一样。

    为了学习效果更好一点,在这里把代码都放出来,方便大家运行代码

   首先,当然是SpringBootApplication启动入口  

package com.springboot;

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


@SpringBootApplication
@MapperScan("com.springboot.repository")
public class MybatisApplication {

	public static void main(String[] args) {
		
		SpringApplication app = new SpringApplication(MybatisApplication.class);
		app.setDefaultProperties(Collections.singletonMap("server.servlet.context-path", "/webapp"));
		app.run(args);
		
	}
}

      我们从后面开始读取数据库类开始演示代码,操作数据库就是这个接口类,,虽然是接口,但是Mybatis帮你实现了,我们不用写代码去实现接口里面的方法,需要做的事情就是在接口上增加属性。

     规则也好理解,insert,update,delete,select和原生的SQL语句一样的理解。SQL语句中的参数值就是传进来的实体属性的值,返回数据时实体的属性值就是SQL语句中列的值,通过@Result中property和column对应。看看下面这个接口的写法就明白。

package com.springboot.repository;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.springboot.entity.ProductOrder;

public interface ProductOrderRepository {

	@Delete("delete from t_ProductOrder where id =#{id}")
	int del(String id);

	@Insert("insert into t_ProductOrder values (#{id},#{name},#{price},getdate())")
    int insert(ProductOrder p);

	@Update("update t_ProductOrder set name = #{name},price = #{price},pDate=getdate() where id =#{id}")
    int update(ProductOrder p);
    
	@Select("SELECT * FROM t_ProductOrder WHERE id = #{id}")
    @Results({ 
    	@Result(property = "name", column = "name"),
    	    @Result(property = "name", column = "name"),
            @Result(property = "price", column = "price"),
            @Result(property = "pDate", column = "pDate")})
    ProductOrder getProductOrder(String id);
    
	@Select("SELECT * FROM t_ProductOrder")
    @Results({ 
    	@Result(property = "name", column = "name"),
    	    @Result(property = "name", column = "name"),
            @Result(property = "price", column = "price"),
            @Result(property = "pDate", column = "pDate")})
    List<ProductOrder> getAllProductOrder();

   
}

   是不是有点似曾相似的感觉。和Hibernate + JPA的模式几乎一模一样。如果看过前面的博文,这个理解起来就很容易了。接下来就是为Controller

package com.springboot.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;  
import com.springboot.entity.ProductOrder;
import com.springboot.service.IProcducOrderService;

@RestController
@RequestMapping("/product")
public class ProductOrderController {
	
    @Resource
    private IProcducOrderService procductService;

    @RequestMapping("/query")
    @ResponseBody
    public ProductOrder query(HttpServletRequest request){
        
    	String id = request.getParameter("id");
        
        return this.procductService.getProductOrderById(id);
    }

    @RequestMapping("/getall")
    @ResponseBody
    public List<ProductOrder> getall()
    {
        return this.procductService.getAllProductOrder();
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(ProductOrder m)
    {
    	UUID uuid = UUID.randomUUID(); 
    	
    	m.setId(uuid.toString());
        
    	int i = this.procductService.addProductOrder(m);
        
        return "{'success' : true,'msg':'','count':'"+ i +"'}".replaceAll("'","\"");
    }
}

   interface 接口类

package com.springboot.service;

import java.util.List;

import com.springboot.entity.ProductOrder;

public interface IProcducOrderService {
	
    ProductOrder getProductOrderById(String id);

    int addProductOrder(ProductOrder m);
    
    List<ProductOrder> getAllProductOrder();
}

   ProductOrderServiceImpl 继承上面接口实现类

package com.springboot.service;

import org.springframework.stereotype.Service;
import com.springboot.entity.ProductOrder;
import com.springboot.repository.ProductOrderRepository;

import java.util.List;

import javax.annotation.Resource;

@Service
public class ProductOrderServiceImpl implements IProcducOrderService {

    @Resource
    private ProductOrderRepository db;

    @Override
    public ProductOrder getProductOrderById(String id)
    {
    	return db.getProductOrder(id);
    }

    @Override
    public int addProductOrder(ProductOrder m)
    {
    	
    	return db.insert(m);
    }
    
    @Override
    public List<ProductOrder> getAllProductOrder()
    {
    	return db.getAllProductOrder();
    	
    }

}

ProductOrder 实体类

package com.springboot.entity;

import java.util.Date;

public class ProductOrder {
	
    private String id;

    private String name;

    private float price;

    private Date pDate;
    
    public String getId() {
        return id;
    }

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

    public String getName() {
        return this.name;
    }

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

    public float getPrice() {
        return this.price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public Date getPDate() {
        return this.pDate;
    }

    public void setPDate(Date pDate) {
        this.pDate = pDate;
    }
}

    静态页面 index.html

   

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>springboot服务接口测试</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
        	//query();
        });      

        function query(){
			var url = "product/getall";
        	ActionPostData(url, "GET", "", load);
        };
        
        function add(){
			var url = "product/save";    	
			var data = {"id":"","name":"测试","price":0.32,"pDate":new Date()};
        	ActionPostData(url, "POST", data, load);
        	
        	query();
        }
        
        function load(data) {
            $("#div1").html('');
            $("#div1").html(JSON.stringify(data));
        };
		
        function ActionPostData(url, mType, o, fn) {
            $.ajax({
                url: url,
                type: mType,
                cache: false,
                dataType: "json",
                data: o,
                success: fn
            }
        );
        };
  </script>
</head>
<body>
    <input type="button" value="查询" name="w4" onclick="query()"/>
    <input type="button" value="add" name="w5" onclick="add()"/>
    <div style="margin-top:10px;margin-bottom:10px;color:blue" id="div1"></div>
</body>
</html>

      resources/static下 配置文件 application.properties

server.port=8181

# mybatis 
#mybatis.type-aliases-package=com.springboot.entity
#mybatis.mapper-locations=classpath:mapper/*.xml
#mybatis.configuration.map-underscore-to-camel-case=true

#sqlserver
spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=yourdatabase
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

     除了操作的接口类以外,剩下的这几个类和上一个博文中一样,没有任何区别。这就是Springboot的使用Mybatis框架的另外一种方式实现了一遍。

    是不是有点啰嗦了?对于初学者来说,看一篇文章只要能明白一个知识点,就够了。

   不断坚持,不断积累,很快就会有收获。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值