springData__jpa对数据库进行操作---dao接口和 测试类
Posted 躺床上看天dzl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springData__jpa对数据库进行操作---dao接口和 测试类相关的知识,希望对你有一定的参考价值。
一、dao接口
采用方法命名规则,对数据库进行操作
前提是接口必须继承 JPARepository类
package cn.dzl.jpa.dao; import cn.dzl.jpa.entity.Customer; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CustomerDao extends JpaRepository<Customer,Long> { //方法命名规则 public Customer findByCustId(long id); //模糊查询 public List<Customer>findByCustNameLike(String CustName); //删除 public void deleteByCustId(long id); //多条件模糊查询 public List<Customer>findByCustNameLikeAndCustAddressLike(String CustName,String CustAddress); //查数 public long count(); //通过姓名查找 public List<Customer> findByCustName(String custName); }
二、测试类
import cn.dzl.jpa.dao.CustomerDao; import cn.dzl.jpa.entity.Customer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Commit; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class JpaTest { @Autowired CustomerDao customerDao; @Test public void findById(){ Customer customer = customerDao.findByCustId(6L); System.out.println(customer); } //模糊查询 @Test public void findByCustNameLike(){ List<Customer> customerList = customerDao.findByCustNameLike("%aa%"); for (Customer customer : customerList) { System.out.println(customer); } } //删除 @Test public void deleteByCustId(){ customerDao.deleteByCustId(5L); Customer customer = customerDao.findByCustId(5L); if (customer==null){ System.out.println("删除成功"); }else{ System.out.println("删除失败"); } } //模糊查询 @Test public void findByCondition(){ List<Customer> customerList = customerDao.findByCustNameLikeAndCustAddressLike("%哈%", "%金%"); for (Customer customer : customerList) { System.out.println(customer); } } //查数 @Test public void count(){ long count = customerDao.count(); System.out.println(count); } //保存 @Test public void save(){ Customer customer = new Customer(); customer.setCustName("aa"); customer.setCustPhone("123456"); customer.setCustLevel("5"); customer.setCustAddress("郑州"); customer.setCustSource("未知"); customerDao.save(customer); List<Customer> customerList = customerDao.findByCustName("aa"); if (customerList!=null){ System.out.println("添加成功"); for (Customer customer1 : customerList) { System.out.println(customer1); } }else{ System.out.println("添加失败"); } } }
以上是关于springData__jpa对数据库进行操作---dao接口和 测试类的主要内容,如果未能解决你的问题,请参考以下文章