CrudRepository 的主要方法
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 里面实现了大量的增删改查方法
package org.springdata.repository; import org.springdata.domain.Employee; import org.springframework.data.repository.CrudRepository; /** * */ public interface CurdEmployeeRespository extends CrudRepository<Employee, Integer> { }
2. 编写service实现类
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(); } }
测试结果
因为我测试前把数据全部都删除了