spring boot整合Spring-data-jpa自定义扩展接口
- 基于Spring boot1.5.9.RELEASE和JDK1.8
1、添加Maven依赖
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
2、配置数据源
application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver #mysql连接配置
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username: root
password: root
jpa:
show-sql: true
hibernate:
ddl-auto: update
3、创建公共Base接口
公共接口声明BaseJpaRepository.java
package com.lilian.base.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import java.io.Serializable;
import java.util.List;
/**
* jpa-demo
* 为全部的Repository 声明一些自定义方法的接口
*
* @Author 孙龙
* @Date 2018/7/2
*/
@NoRepositoryBean
public interface BaseJpaRepository extends JpaRepository, JpaSpecificationExecutor {
/**
* 查询多个属性
* 返回List
- 需要添加
@NoRepositoryBean
注解来说明此接口不是一个声明的Repository,否则Spring默认当做普通的Repository来处理; - 可以在此接口中生命一些自定义的接口公共方法;
- 在这里同时继承了JpaSpecificationExecutor类,支持了Specification方式的复杂查询方式,普通的Repository接口在使用Specification查询就无须使用多继承或选择继承的方式
公共接口实现类SimpleBaseJpaRepository.java
package com.lilian.base.jpa;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;
/**
* jpa-demo 公共Jpa接口实现类
*
* @Author 孙龙
* @Date 2018/7/2
*/
public class SimpleBaseJpaRepository
extends SimpleJpaRepository implements BaseJpaRepository {
private final EntityManager entityManager;
private Class clazz;
public SimpleBaseJpaRepository(Class domainClass, EntityManager em) {
super(domainClass, em);
this.clazz = domainClass;
this.entityManager = em;
}
@Override
public List sqlArrayList(String sql) {
Query query = entityManager.createNativeQuery(sql);
List list = query.getResultList();
entityManager.close();
return list;
}
@Override
public List sqlObjectList(String sql, Object obj) {
Query query = entityManager.createNativeQuery(sql, obj.getClass());
List list = query.getResultList();
entityManager.close();
return list;
}
@Override
public List sqlSingleList(String sql) {
Query query = entityManager.createNativeQuery(sql);
List list = query.getResultList();
entityManager.close();
return list;
}
}
4、重写JpaRepositoryFactoryBean中的方法
package com.lilian.base.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import javax.persistence.EntityManager;
import java.io.Serializable;
/**
* jpa-demo
* 自定义扩展后的factoryBean
*
* @Author 孙龙
* @Date 2018/7/2
*/
public class BaseJpaRepositoryFactoryBean, T, I extends Serializable>
extends JpaRepositoryFactoryBean {
public BaseJpaRepositoryFactoryBean(Class extends R> repositoryInterface) {
super(repositoryInterface);
}
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new BaseDaoFactory(entityManager);
}
private static class BaseDaoFactory
extends JpaRepositoryFactory {
private final EntityManager entityManager;
public BaseDaoFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
@Override
protected Object getTargetRepository(RepositoryInformation information) {
return new SimpleBaseJpaRepository((Class) information.getDomainType(), entityManager);
}
@Override
protected Class> getRepositoryBaseClass(RepositoryMetadata metadata) {
return SimpleBaseJpaRepository.class;
}
}
}
5、覆盖SpringBoot提供的默认配置
package com.lilian.base;
import com.lilian.base.mysql.BaseJpaRepositoryFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
* jpa-demo
* 自定义jpa配置类
*
* @Author 孙龙
* @Date 2018/7/2
*/
@Configuration
@EnableJpaRepositories(basePackages = {"com.lilian.repository.mysql"}, repositoryFactoryBeanClass = BaseJpaRepositoryFactoryBean.class)
public class JpaRepositoryConfig {
}
这里的basePackages
参数需要指定Repository所在的包,可以指定多个
6、使用Base接口开发
(1)创建实体类
Person.java
package com.lilian.entity.mysql;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.sql.Timestamp;
/**
* jpa-demo
*
* @Author 孙龙
* @Date 2018/7/3
*/
@Data
@Entity
@NoArgsConstructor
public class Person {
@Id
@GeneratedValue
private Long id;
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 地址
*/
private String address;
/**
* 邮箱
*/
private String email;
/**
* 添加时间
*/
private Timestamp addTime;
/**
* 手机号码
*/
private String phoneNum;
public Person(String name, Integer age, String address, String email, Timestamp addTime, String phoneNum) {
this.name = name;
this.age = age;
this.address = address;
this.email = email;
this.addTime = addTime;
this.phoneNum = phoneNum;
}
}
(2)创建Repo接口
PersonJpaRepository.java
package com.lilian.repository.mysql;
import com.lilian.base.jpa.BaseJpaRepository;
import com.lilian.entity.mysql.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* jpa-demo
*
* @Author 孙龙
* @Date 2018/7/3
*/
public interface PersonJpaRepository extends BaseJpaRepository {
/**
* 根据ID查询全部
*
* @param id
* @return
*/
@Query("select p from Person p where p.id = ?1")
List findById(@Param("id") long id);
}
(3)Service层
IPersonService.java
package com.lilian.service.mysql;
import com.lilian.entity.mysql.Person;
import java.util.List;
/**
* jpa-demo
*
* @Author 孙龙
* @Date 2018/7/3
*/
public interface IPersonService {
/**
* 批量添加
*
* @param personList
*/
void batchAdd(List personList);
/**
* 根据ID查询(@Query方式)
*
* @param id
* @return
*/
List queryById(Long id);
/**
* 根据Addr查询(Specification方式)
*
* @param addr
* @return
*/
List queryByAddr(String addr);
/**
* 根据 phoneNum 查询(Specification方式)
*
* @param phoneNum
* @return
*/
List queryByPhoneNum(String phoneNum);
}
PersonServiceImpl.java
package com.lilian.service.mysql.impl;
import com.lilian.entity.mysql.Person;
import com.lilian.repository.mysql.PersonJpaRepository;
import com.lilian.service.mysql.IPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* jpa-demo
*
* @Author 孙龙
* @Date 2018/7/3
*/
@Service
public class PersonServiceImpl implements IPersonService {
@Autowired
private PersonJpaRepository personRepository;
@Override
public void batchAdd(List personList) {
personRepository.save(personList);
}
@Override
public List queryById(Long id) {
return personRepository.findById(id);
}
@Override
public List queryByAddr(String addr) {
return personRepository.findAll((root, query, cb) -> cb.equal(root.get("address"), addr));
}
@Override
public List queryByPhoneNum(String phoneNum) {
return personRepository.findAll((root, query, cb) -> cb.equal(root.get("phoneNum"), phoneNum));
}
}
7、测试类
PersonServiceImplTest.java
package com.lilian.service.mysql.impl;
import com.lilian.entity.mysql.Person;
import com.lilian.service.mysql.IPersonService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
/**
* jpa-demo
*
* @Author 孙龙
* @Date 2018/7/4
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceImplTest {
@Autowired
private IPersonService personService;
@Test
public void batchAdd() {
List personList = new ArrayList() {{
add(new Person("李四", 25, "北京", "[email protected]", new Timestamp(System.currentTimeMillis() - 10000L), "18844556222"));
add(new Person("张三", 58, "济南", "[email protected]", new Timestamp(System.currentTimeMillis() - 15000L), "16666555222"));
add(new Person("老王", 14, "合肥", "[email protected]", new Timestamp(System.currentTimeMillis() - 20000L), "11222213222"));
add(new Person("赵六", 42, "广州", "[email protected]", new Timestamp(System.currentTimeMillis() - 30000L), "15555433322"));
add(new Person("武大", 63, "上海", "[email protected]", new Timestamp(System.currentTimeMillis() - 40000L), "18766676622"));
add(new Person("孙五", 45, "石家庄", "[email protected]", new Timestamp(System.currentTimeMillis()), "1888888888"));
}};
personService.batchAdd(personList);
}
@Test
public void queryById() {
long id = 1L;
List personList = personService.queryById(id);
for (Person person : personList) {
System.out.println(person);
}
}
@Test
public void queryByAddr() {
String addr = "石家庄";
List personList = personService.queryByAddr(addr);
for (Person person : personList) {
System.out.println(person);
}
}
@Test
public void queryByPhoneNum() {
String phoneNum = "1888888888";
List personList = personService.queryByPhoneNum(phoneNum);
for (Person person : personList) {
System.out.println(person);
}
}
}
Github代码示例
示例中包含Spring data jpa 对Mongo自定义接口的封装和使用