Spring Data HelloWorld(三)

在 Spring Data 环境搭建(二) 的基础之上 我们改动  

定义个一个接口  继承Repository类  咱们先实现一个根据名字查询

package org.springdata.repository;

import org.springdata.domain.Employee;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;

/***
 *
 */public interface EmployeeRepository extends Repository<Employee,Integer> {
    /**
     * 根据名字找员工
     * desc
     * @param name
     * @return
     */
    public Employee findByName(String name);
}

大家可以发现 我只声明了一个方法 并没有写任何的实现类 哦了 就这样 咱们写个实现类

package org.springdata;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springdata.domain.Employee;
import org.springdata.repository.EmployeeRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试类
 */
public class SpringDataTest {

    private ApplicationContext ctx = null;

    private EmployeeRepository employeeRepository = null;

    @Before
    public void setup(){
        ctx = new ClassPathXmlApplicationContext("beans.xml");
        employeeRepository = (EmployeeRepository)ctx.getBean(EmployeeRepository.class);
        System.out.println("setup");
    }

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

    @Test
    public void testEntityManagerFactory(){

    }

    @Test
    public void testFindByName(){
        System.out.println(employeeRepository);
        Employee employee = employeeRepository.findByName("zhangsan");
        System.out.println("id:" + employee.getId()
                + " , name:" + employee.getName()
                + " ,age:" + employee.getAge());
    }
}

根据用户名查询用户信息

就这样   简缩了jdbc的繁琐操作 ,你们是不是要试一试呢

猜你喜欢

转载自blog.csdn.net/weixin_42722953/article/details/89518341