spring-boot-maven-plugin
在application.properties文件中配置数据库的链接。
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.servlet.multipart.max-request-size=2048MB
spring.servlet.multipart.max-file-size=2048MB
server.port=8080
在写代码之前,我们先来看一下项目的目录结构。
代码实现
对持久层的封装,我们首先需要确定的就是找到对应的实体类,之后才能对其进行操作,可以通过反射机制找到当前的实体类。
新建一个反射工具类GenericsUtils,这个类很重要,可以帮助我们找到对应的实体类。
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericsUtils {
/**
-
通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
-
GenricManager
-
@param clazz The class to introspect
-
@return the first generic declaration, or
Object.class
if cannot be determined
*/
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
-
通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager
-
@param clazz clazz The class to introspect
-
@param index the Index of the generic ddeclaration,start from 0.
*/
public static Class getSuperClassGenricType(Class clazz, int index)
throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}
新建CommonRepository接口,为公共的Reposit接口,该类继承JpaRepository,JpaSpecificationExecutor两个接口,这两个接口中包含了基本的查询。之后在新建Repository就可以直接继承这个公共的CommonRepository接口就可以了,有两个泛型接口,实体类名称和id的类型,T表示实体类名称,ID表示id的类型。代码如下。
@NoRepositoryBean
public interface CommonRepository<T,ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor {
}
新建CommonService类,为公共的Server类,包含了一下基本查询的方法,之后的Server类,只需要继承这个类,就会包含CommonService类中的所有查询方法,不用在每个类都去写一遍,如果有需要更改的话,可以重写继承类中的方法。和Repository接口一样,它也有有两个泛型接口,实体类名称和id的类型,T表示实体类名称,ID表示id的类型。代码如下。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
i