Spring Data HelloWorld(三)

本文介绍如何使用SpringData简化数据库操作,通过定义Repository接口及其实现类,实现根据员工姓名查询详细信息的功能,展示了SpringData的便捷性和高效性。

在 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的繁琐操作 ,你们是不是要试一试呢
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值