Spring Date JPA实现增删改查
1.新建一个Cart类
package com.entity;
public class Cart {
private int id;
private int userId;
private int medicineId;
private int count;
private int price;
private String medicineName;
private String medicineSize;
private int status;
}
2.添加注解
@Entity //表示是一个实体类
@Table(name = "tbl_cart") //指定数据库中对应的表
public class Cart {
@Id //指定主键
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增
private int id;
private int userId;
private int medicineId;
private int count;
private int price;
private String medicineName;
private String medicineSize;
private int status;
}
后面添加get、set方法和toString方法
3.创建实体类的CartRepository接口
package com.Dao;
import com.entity.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CartRepository extends JpaRepository<Cart,Integer> {
}
接口继承JpaRepository<操作的实体类,主键类型>
接口默认实现了增删改查等一些简单的操作,其他操作可以参考Spring Data JPA根据属性名查询在接口类中直接创建。
4.创建CartService类
创建CartService类然后添加service层注解,然后在类中实现各种方法。
package com.service;
import com.Dao.CartRepository;
import com.entity.Cart;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CartService {
@Resource
CartRepository cartRepository;
//查询全部
public List<Cart> findAll(){
return this.cartRepository.findAll();
}
}
5.创建CartController
RestController只能返回String类型的数据
package com.controller;
import com.entity.Cart;
import com.google.gson.Gson;
import com.service.CartService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/cart")
public class CartController {
@Resource
CartService cartService;
Gson gson = new Gson();
//获取所有购物车信息
@RequestMapping(value = "/list")
public String list()
{
List<Cart> cartList = this.cartService.findAll();
String result = gson.toJson(cartList);
return result;
}
}
6.通过post或者get请求访问服务器
http://localhost:8070/onepill/cart/list
参考:JPA概述
本文来自博客园,作者:两小无猜,转载请注明原文链接:https://www.cnblogs.com/charlottepl/p/12656183.html