Spring Data CrudRepository增刪改查方法(八)

 

  CrudRepository   的主要方法java

long count();   
boolean exists(Integer arg0);  
  
<S extends StudentPO> S save(S arg0);  
<S extends StudentPO> Iterable<S> save(Iterable<S> arg0);  
  
void delete(Integer arg0);  
void delete(Iterable<? extends StudentPO> arg0);  
void delete(StudentPO arg0);  
void deleteAll();  
  
StudentPO findOne(Integer arg0);  
Iterable<StudentPO> findAll();  
Iterable<StudentPO> findAll(Iterable<Integer> arg0);  

1. 新建一個類 CurdEmployeeRespository   繼承CrudRepository  裏面實現了大量的增刪改查方法spring

package org.springdata.repository;

import org.springdata.domain.Employee;
import org.springframework.data.repository.CrudRepository;

/**
 *
 */
public interface CurdEmployeeRespository extends CrudRepository<Employee, Integer> {

}

2. 編寫service實現類dom

  

package org.springdata.service;

import org.springdata.domain.Employee;
import org.springdata.repository.CurdEmployeeRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 */

@Service
public class CrudEmployeeService {

    @Autowired
    private CurdEmployeeRespository employeeRespository;


    @Transactional
    public void save(){
        Employee employee = new Employee();
        employee.setName("zhangzy");
        employee.setAge(12);
        employeeRespository.save(employee);
    }
}

編寫測試類測試

  

package org.springdata.crudservice;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springdata.repository.CurdEmployeeRespository;
import org.springdata.repository.EmployeeRepository;
import org.springdata.service.CrudEmployeeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 */
public class CurdServiceTest {

    private ApplicationContext ctx = null;

    private CrudEmployeeService crudEmployeeService = null;

    @Before
    public void setup(){
        ctx = new ClassPathXmlApplicationContext("beans_news.xml");
        crudEmployeeService = ctx.getBean(CrudEmployeeService.class);
        System.out.println("setup");
    }

    @After
    public void tearDown(){
        ctx = null;
        System.out.println("tearDown");
    }


    @Test
    public void save(){
        crudEmployeeService.save();
    }
}

測試結果code

   由於我測試前把數據所有都刪除了xml

相關文章
相關標籤/搜索