1 spring data jpa
虽然说spring data 提供了很多DAO 接口,但是依然可能不能满足我们日常的使用,所以,有时我们需要自定义接口方法。自定义接口方法步骤如下:
1. 创建自定义工厂类:CustomerJpaRepositoryFactoryBean, 需要继承JpaRepositoryFactoryBean
package org.zgf.spring.data.customer; import java.io.Serializable; import javax.persistence.EntityManager; import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport; /**
* 自定义工厂
* @author: zonggf
* @date: 2016年1月18日-下午2:16:18
*/
public class CustomerJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable>
extends JpaRepositoryFactoryBean<T, S, ID> { @Override
protected RepositoryFactorySupport createRepositoryFactory(
EntityManager entityManager) {
return new CustomerRepositoryFactory(entityManager);
} private static class CustomerRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory { private EntityManager entityManager; public CustomerRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
} protected Object getTargetRepository(RepositoryMetadata metadata) {
return new IBaseDaoImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
} protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return IBaseDao.class;
}
}
}
2. 创建自定义接口:IBaseDao, 需要继承JpaRepository
package org.zgf.spring.data.customer; import java.io.Serializable; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean; //必须使用该注解标明,此接口不是一个Repository Bean
@NoRepositoryBean
public interface IBaseDao <T, ID extends Serializable> extends JpaRepository<T, ID>{ //自定义接口方法
public void sayHello(String name); }
3. 创建自定义接口实现 类:IBaseDaoImpl, 名称必须是 接口名+ Impl
package org.zgf.spring.data.customer; import java.io.Serializable; import javax.persistence.EntityManager; import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
//必须使用该注解标明,此接口不是一个Repository Bean
@NoRepositoryBean
public class IBaseDaoImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
implements IBaseDao<T, ID> { private EntityManager entityManager; public IBaseDaoImpl(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
this.entityManager = em;
} @Override
public void sayHello(String name) {
System.out.println("entityManage:" + entityManager);
System.out.println("hello, " + name);
}
}
4. 配置文件中配置自定义工厂类:
<!-- 5. 配置 SpringData -->
<!-- 加入 jpa 的命名空间 扫描 Repository Bean 所在的 package, 自定义工厂类 -->
<jpa:repositories base-package="org.zgf.spring.data" entity-manager-factory-ref="entityManagerFactory" factory-class="org.zgf.spring.data.customer.CustomerJpaRepositoryFactoryBean"/>
5. 测试类