1. 程式人生 > 其它 >spring-data-jpa(單表增刪改查)

spring-data-jpa(單表增刪改查)

技術標籤:後端

上一篇:建表
dao層


import com.example.demo.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<
Customer
>
{ }

service層


public interface CustomerService {
    Customer findOne(Long id);

    void save(Customer customer);

    void delete(Long id);

   
}

service實現層

@Service
public class CustomerImpl implements CustomerService {
    @Autowired
    CustomerDao customerDao;

    @Override
    public Customer findOne(Long id) {
        return customerDao.getOne(id);
    }

    @Override
    public void save(Customer customer) {
        customerDao.save(customer);
    }

    @Override
    public void delete(Long id) {
        customerDao.deleteById(id);
    }
}

Controller層


@RestController
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    CustomerImpl customerImpl;
    @Autowired
    LinkManImpl linkManImpl;
    @Autowired
    RoleImpl roleImpl;

    @Transactional
    @Rollback(value = false)
    @RequestMapping("save")
    void save(String name, Long id) {
        Customer customer = new Customer();
        customer.setCustId(id);
        customer.setName(name);
        customerImpl.save(customer);
    }

    @RequestMapping("getOne")
    Customer getOne(Long id) {
        return customerImpl.findOne(id);
    }

    @Transactional
    @Rollback(value = false)
    @RequestMapping("delete")
    void delete(Long id) {
        customerImpl.delete(id);
    }

}

**

新增

**
http://localhost:8080/customer/save?name=bill&id=1
控制檯列印
在這裡插入圖片描述
資料庫表資料已經插入
在這裡插入圖片描述

更新

http://localhost:8080/customer/save?name=BILL&id=1
控制檯列印

表資料已經更新
在這裡插入圖片描述

查詢

http://localhost:8080/customer/getOne?id=1
控制檯列印
在這裡插入圖片描述
網頁結果
在這裡插入圖片描述

刪除

http://localhost:8080/customer/delete?id=1
控制檯列印
在這裡插入圖片描述
資料庫表中已經沒有了該記錄
在這裡插入圖片描述
下一篇:分頁、排序