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 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 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 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 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
springboot服务接口测试
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框架的另外一种方式实现了一遍。
是不是有点啰嗦了?对于初学者来说,看一篇文章只要能明白一个知识点,就够了。
不断坚持,不断积累,很快就会有收获。