Jpadao層接口
package cn.itcast.dao;
import cn.itcast.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/*
* 符合SpringDataJpa的dao層接口規(guī)范
* JpaRepository<操作的實(shí)體類泛型,實(shí)體類中主鍵屬性的類型>
* *封裝了基本增刪改查操作
* JpaSpecificationExecutor<操作的實(shí)體類類型>
* *封裝了復(fù)雜查詢(分頁)
* */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
測試增刪改查
package cn.itcast.test;
import cn.itcast.entity.Customer;
import cn.itcast.dao.CustomerDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)//聲明spring提供的單元測試環(huán)境
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao;
/*
* 根據(jù)id查詢
* */
@Test
public void testFindOne(){
Customer one = customerDao.findOne(3l);
System.out.println(one);
}
/*
* save:保存或者更新
* 根據(jù)傳遞對象是否存在主鍵id
* 如果沒有主鍵id屬性,保存
* 存在主鍵id屬性,根據(jù)id查詢數(shù)據(jù)皿曲,更新數(shù)據(jù)
* */
@Test
public void testSave(){
Customer customer = new Customer();
customer.setCustName("小李子");
customer.setCustLevel("vip");
customer.setCustIndustry("it教育");
customerDao.save(customer);
}
@Test
public void testUpData(){
Customer customer = customerDao.findOne(3l);
customer.setCustName("劉強(qiáng)東");
customerDao.save(customer);
}
/*
*刪除用戶
* */
@Test
public void testDelete(){
customerDao.delete(6l);
}
/*
*查詢所有
**/
@Test
public void testFindALll(){
List<Customer> all = customerDao.findAll();
for (Customer customer:all){
System.out.println(customer);
}
}
/*
* 測試統(tǒng)計(jì)查詢:查詢客戶的總數(shù)量
* */
@Test
public void testCount(){
long count = customerDao.count();
System.out.println(count);
}
/*
*測試:判斷id為3的客戶是否存在
* 1.可以查詢以下id為3的客戶
* 如果為空状勤,代表不純正,如果不為空畏铆,代表純在
* 2.判斷數(shù)據(jù)庫中id為3的客戶的數(shù)量
* 如果數(shù)量為0雷袋,代表不存在,如果大于0,代表存在
* */
@Test
public void testExists(){
boolean exists = customerDao.exists(3l);
System.out.println(exists);
}
/*
* 根據(jù)id查詢用戶
* findOne:
* em.find() :立即加載
* getOne:
* em.getReference :延遲加載
* *返回的是一個(gè)客戶的動(dòng)態(tài)代理對象
* *什么時(shí)候用楷怒,什么時(shí)候查詢
* */
@Test
@Transactional//保證getOne正常運(yùn)行
public void testGetOne(){
Customer one = customerDao.getOne(3l);
System.out.println(one);
}
}
image.png