1 jpa原生(框架搭建见3)
1.1 jpa原生_查询对象
dao
/** * 根据主键查询,最开始用的是findById,后来因为某种原因废弃掉了 * @author weidoudou * @date 2022/8/4 7:52 * @param inputPropertyA 请添加参数描述 * @return com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei **/ @Query(value = "select * from t_ddwei where INPUT_PROPERTY_A = ?1",nativeQuery = true) TDdwei findByInputPropertyA(String inputPropertyA);
测试类:
package com.example.jiayou; import com.alibaba.fastjson.JSON; import com.example.jiayou.ceshi.TDdwei; import com.example.jiayou.ceshi.TDdweiDao2; import lombok.extern.slf4j.Slf4j; 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; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = JiayouApplication.class) public class DdweiDaoTest { @Autowired TDdweiDao2 tDdweiDao2; @Test public void Test(){ //DdweiEntity entity = DdweiEntity.builder().inputPropertyA("0003").inputPropertyB("曹操").build(); //查询测试 TDdwei tDdwei = tDdweiDao2.findByInputPropertyA("0001"); System.out.println("DdweiDaoTest->Test->OutPutParm->"+ JSON.toJSONString(tDdwei)); //修改测试 /*TDdwei tDdwei2 = new TDdwei(); tDdwei2.setInputPropertyA("0003"); tDdwei2.setInputPropertyB("关羽"); tDdweiDao2.save2(tDdwei2);*/ } }
测试结果:
DdweiDaoTest->Test->OutPutParm->{"inputPropertyA":"0001","inputPropertyB":"11","outputPropertyA":"222"}
1.2 jpa原生_查询列表
dao
/** * 查询列表 * @author weidoudou * @date 2022/8/4 7:52 * @param inputPropertyA 请添加参数描述 * @return com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei **/ @Query(value = "select * from t_ddwei where INPUT_PROPERTY_A like %?1%",nativeQuery = true) List<TDdwei> findListByInputPropertyA(String inputPropertyA);
测试类:
@Test public void Test(){ //DdweiEntity entity = DdweiEntity.builder().inputPropertyA("0003").inputPropertyB("曹操").build(); //查询测试 /*TDdwei tDdwei = tDdweiDao2.findByInputPropertyA("0001"); System.out.println("DdweiDaoTest->Test->OutPutParm->"+JSON.toJSONString(tDdwei));*/ //修改测试 /*TDdwei tDdwei2 = new TDdwei(); tDdwei2.setInputPropertyA("0003"); tDdwei2.setInputPropertyB("关羽"); tDdweiDao2.save2(tDdwei2);*/ //查询测试List List<TDdwei> tDdwei = tDdweiDao2.findListByInputPropertyA("000"); System.out.println("DdweiDaoTest->Test->OutPutParm->"+ JSON.toJSONString(tDdwei)); }
测试结果:
DdweiDaoTest->Test->OutPutParm-> [ {"inputPropertyA":"0001","inputPropertyB":"11","outputPropertyA":"222"}, {"inputPropertyA":"0002","inputPropertyB":"22","outputPropertyA":"333"}, {"inputPropertyA":"0003","inputPropertyB":"关羽"} ]
1.3 jpa原生_修改
dao
package com.example.jiayou.ceshi; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional(rollbackFor = Exception.class) public interface TDdweiDao2 extends JpaRepository<TDdwei,String> { /** * 根据主键查询,最开始用的是findById,后来因为某种原因废弃掉了 * @author weidoudou * @date 2022/8/4 7:52 * @param inputPropertyA 请添加参数描述 * @return com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei **/ @Query(value = "select * from t_ddwei where INPUT_PROPERTY_A = ?1",nativeQuery = true) TDdwei findByInputPropertyA(String inputPropertyA); @Modifying @Query(value = "update t_ddwei t set t.INPUT_PROPERTY_B=:#{#po.inputPropertyB} where t.INPUT_PROPERTY_A=:#{#po.inputPropertyA}",nativeQuery = true) int save2(TDdwei po); }
测试类:
package com.example.jiayou; import com.example.jiayou.ceshi.TDdwei; import com.example.jiayou.ceshi.TDdweiDao2; import lombok.extern.slf4j.Slf4j; 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; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = JiayouApplication.class) public class DdweiDaoTest { @Autowired TDdweiDao2 tDdweiDao2; @Test public void Test(){ //DdweiEntity entity = DdweiEntity.builder().inputPropertyA("0003").inputPropertyB("曹操").build(); //查询测试 /*TDdwei tDdwei = tDdweiDao2.findByInputPropertyA("0001"); System.out.println("DdweiDaoTest->Test->OutPutParm->"+JSON.toJSONString(tDdwei));*/ //修改测试 TDdwei tDdwei2 = new TDdwei(); tDdwei2.setInputPropertyA("0003"); tDdwei2.setInputPropertyB("关羽"); tDdweiDao2.save2(tDdwei2); } }
测试结果:
注意:
- 有nativeQuery = true时,是可以执行原生sql语句,所谓原生sql,也就是说这段sql拷贝到数据库中,然后把参数值给一下就能运行了
- @Transactional(rollbackFor=Exception.class),如果类加了这个注解,那么这个类里面的方法抛出异常,就会回滚,数据库里面的数据也会回滚
- 涉及到数据修改操作,可以使用 @Modifying 注解
2 jpa封装(框架搭建见3)
2.1 jpa封装_不同字段判断
- String类型,见2
- Date类型:大于
if(entity.getInputPropertyA()!=null){ preList.add(criteriaBuilder.greaterThan(root.get("inputPropertyA"),entity.getInputPropertyA())); }
2.2 jpa封装_常见逻辑类型
- in类型
if(!CollectionUtils.isEmpty(entity.getAList())){ Path<Object> path = root.get("inputPropertyA"); CriteriaBuilder.In<Object> in = criteriaBuilder.in(path); entity.getAList().forEach(e->{ in.value(e); }); Predicate predicate = criteriaBuilder.and(in); preList.add(predicate); }
- where类型 见2
- order by类型
criteriaQuery.orderBy(criteriaBuilder.desc(root.get("inputPropertyA")));
2.3 jpa封装_分页 (结合2看)
DdweiRepository
/** * 根据do查找dolist * @author weidoudou * @date 2022/8/7 17:35 * @param entity 请添加参数描述 * @return java.util.List<com.ddwei.domain.moduleA.domainobject.DdweiEntity> **/ PageResult<DdweiEntity> findAllPage(DdweiEntity entity, Pageable pageable);
DdweiRepositoryImpl
@Override public PageResult<DdweiEntity> findAllPage(DdweiEntity entity, Pageable pageable) { Page<TDdwei> page = tDdweiDao.findAll(new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> preList = new ArrayList<>(); if(StringUtils.isNotBlank(entity.getInputPropertyA())){ preList.add(criteriaBuilder.equal(root.get("inputPropertyA").as(String.class),entity.getInputPropertyA())); } if(StringUtils.isNotBlank(entity.getInputPropertyB())){ preList.add(criteriaBuilder.equal(root.get("inputPropertyB").as(String.class),entity.getInputPropertyB())); } criteriaQuery.where(preList.toArray(new Predicate[preList.size()])); return criteriaQuery.getRestriction(); } },pageable); PageResult<DdweiEntity> pageResult = new PageResult<>(pageable.getPageNumber(),pageable.getPageSize(), page.getTotalPages(),page.getTotalElements(),Optional.ofNullable(page).map( listE->{ return listE.stream().map(DDweiConverter.INSTANCE::toDomainObject).collect(Collectors.toList()); } ).orElse(new ArrayList<>())); return pageResult; }
PageResult_自己新建的
@Setter @Getter @NoArgsConstructor @AllArgsConstructor public class PageResult<T> implements Serializable { private int pageNo; private int pageSize; private int totalPage; private long total; private List<T> list; public PageResult(Page<T> page){ this.pageNo = page.getNumber()+1; this.pageSize = page.getSize(); this.total = page.getTotalElements(); this.totalPage = page.getTotalPages(); this.list = page.getContent(); } }
Service
PageResult<CallServerDto> methodC(PageParm<CallServerDto> pageParm) throws DBusinessException;
ServiceImpl
@Override public PageResult<CallServerDto> methodC(PageParm<CallServerDto> pageParm) throws DBusinessException { if(ObjectUtils.isEmpty(pageParm)||ObjectUtils.isEmpty(pageParm.getData())|| StringUtils.isEmpty(pageParm.getData().getOutputPropertyA())){ throw new DBusinessException("1111111","参数不许为空","ddwei"); } DdweiEntity queryDo = DdweiEntity.builder().outputPropertyA("张飞").build(); PageResult<DdweiEntity> doPageResult = ddweiRepository.findAllPage(queryDo,pageParm.getPageNo()==0 ? PageRequest.of(pageParm.getPageNo(),pageParm.getPageSize()) :PageRequest.of(pageParm.getPageNo()-1,pageParm.getPageSize())); if(doPageResult.getTotal()==0){ return new PageResult<>(pageParm.getPageNo(),pageParm.getPageSize(),0,0,new ArrayList<>()); } List<CallServerDto> dtoList = doPageResult.getList().stream().map( e->{ return DDweiConverter.INSTANCE.doToDto(e); } ).collect(Collectors.toList()); return new PageResult<>(doPageResult.getPageNo()+1, doPageResult.getPageSize(),doPageResult.getTotalPage(),doPageResult.getTotal(),dtoList); }
测试入参
{ "interfaceName":"com.ddwei.application.moduleA.service.impl.CallServerServiceImpl", "methodName":"methodC", "paramsList":[{ "index":"1", "type":"com.ddwei.api.temp.jarBao.PageParm", "fanxingClass":"com.ddwei.api.bff.moduleA.dto.response.CallServerDto", "fanxingFieldName":"data", "data":{ "data":{ "user":{ "userId":1222, "orgId":"11" }, "outputPropertyA":"张飞" }, "pageNo":1, "pageSize":100 } }] }
测试结果
2.4 jpa封装_update_结合2看
功能点:
因为jpa update entity经常会出现本条案例为空的情况,所以,一般我们都是先查出唯一的一条,然后进行change方法,update,这样就不会出现参数缺失的情况。
Repository
/** * 保存do * @author weidoudou * @date 2022/2/19 12:50 * @param entity 请添加参数描述 * @return com.ddwei.domain.moduleA.domainobject.DdweiEntity **/ DdweiEntity saveOrUpdate(DdweiEntity entity);
RepositoryImpl
@Override public DdweiEntity saveOrUpdate(DdweiEntity entity) { TDdwei tDdwei = dDweiConverter.toPo(entity); return dDweiConverter.toDomainObject(tDdweiDao.saveAndFlush(tDdwei)); }
测试类
package com.example.jiayou; import com.alibaba.fastjson.JSON; import com.example.jiayou.ceshi.DdweiEntity; import com.example.jiayou.ceshi.DdweiRepository; import com.example.jiayou.ceshi.PageResult; import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONArray; 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.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = JiayouApplication.class) public class DdweiRepositoryImplTest { @Autowired DdweiRepository ddweiRepository; @Test public void Test(){ DdweiEntity entity = DdweiEntity.builder().inputPropertyA("0003").inputPropertyB("曹操").build(); //List<DdweiEntity> entityList = ddweiRepository.findAllList(entity); //log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(entityList)); /*PageResult<DdweiEntity> pageResult = ddweiRepository.findAll(entity, PageRequest.of(0,1)); log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(pageResult));*/ /*List<DdweiEntity> entityList = ddweiRepository.findAndOrAndList(entity); log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(entityList));*/ //修改测试 DdweiEntity entity1 = ddweiRepository.saveOrUpdate(entity); log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(entity1)); } }
结果:
2.5 jpa封装_两个与一个或查询_结合2看
需求:
查询(inputPropertyB为11,outputPropertyA为222) 或者(inputPropertyB为22,outputPropertyA为333)
Repository
/**
* 需求:查询(inputPropertyB为11,outputPropertyA为222) 或者(inputPropertyB为22,outputPropertyA为333)
* @author weidoudou
* @date 2022/8/7 17:35
* @param entity 请添加参数描述
* @return java.util.List<com.ddwei.domain.moduleA.domainobject.DdweiEntity>
**/
List<DdweiEntity> findAndOrAndList(DdweiEntity entity);
RepositoryImpl
/**
* 需求:查询(inputPropertyB为11,outputPropertyA为222) 或者(inputPropertyB为22,outputPropertyA为333)
* @author weidoudou
* @date 2022/8/17 7:14
* @param entity 请添加参数描述
* @return java.util.List<com.example.jiayou.ceshi.DdweiEntity>
**/
@Override
public List<DdweiEntity> findAndOrAndList(DdweiEntity entity) {
List<TDdwei> list = tDdweiDao.findAll(new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
//子查询1
Subquery<TDdwei> subquery1 = criteriaQuery.subquery(TDdwei.class);
Root<TDdwei> subRoot1 = subquery1.from(TDdwei.class);
subquery1.select(subRoot1.get("inputPropertyA"));
List<Predicate> subPredicates1 = new ArrayList<>();
subPredicates1.add(criteriaBuilder.equal(subRoot1.get("inputPropertyB").as(String.class),"11"));
subPredicates1.add(criteriaBuilder.equal(subRoot1.get("outputPropertyA").as(String.class),"222"));
subquery1.where(subPredicates1.toArray(new Predicate[subPredicates1.size()]));
//子查询2
Subquery<TDdwei> subquery2 = criteriaQuery.subquery(TDdwei.class);
Root<TDdwei> subRoot2 = subquery2.from(TDdwei.class);
subquery2.select(subRoot2.get("inputPropertyA"));
List<Predicate> subPredicates2 = new ArrayList<>();
subPredicates2.add(criteriaBuilder.equal(subRoot2.get("inputPropertyB").as(String.class),"22"));
subPredicates2.add(criteriaBuilder.equal(subRoot2.get("outputPropertyA").as(String.class),"333"));
subquery2.where(subPredicates2.toArray(new Predicate[subPredicates2.size()]));
//合并
List<Predicate> preList = new ArrayList<>();
preList.add(criteriaBuilder.or(criteriaBuilder.in(root.get("inputPropertyA")).value(subquery1),criteriaBuilder.in(root.get("inputPropertyA")).value(subquery2)));
criteriaQuery.where(preList.toArray(new Predicate[preList.size()]));
return criteriaQuery.getRestriction();
}
});
//判断非空,po转do
List<DdweiEntity> entityList = Optional.ofNullable(list).map(
listE->{
return listE.stream().map(
e->{
DdweiEntity do2 = dDweiConverter.toDomainObject(e);
return do2;
}
).collect(Collectors.toList());
}
).orElse(new ArrayList<>());
return entityList;
}
测试类:
package com.example.jiayou;
import com.alibaba.fastjson.JSON;
import com.example.jiayou.ceshi.DdweiEntity;
import com.example.jiayou.ceshi.DdweiRepository;
import com.example.jiayou.ceshi.PageResult;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;
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.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JiayouApplication.class)
public class DdweiRepositoryImplTest {
@Autowired
DdweiRepository ddweiRepository;
@Test
public void Test(){
DdweiEntity entity = DdweiEntity.builder().inputPropertyB("11").build();
//List<DdweiEntity> entityList = ddweiRepository.findAllList(entity);
//log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(entityList));
/*PageResult<DdweiEntity> pageResult = ddweiRepository.findAll(entity, PageRequest.of(0,1));
log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(pageResult));*/
List<DdweiEntity> entityList = ddweiRepository.findAndOrAndList(entity);
log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(entityList));
}
}
测试结果:
2022-08-17 07:38:04.410 INFO 54408 --- [ main] c.e.jiayou.DdweiRepositoryImplTest : DdweiRepositoryImplTest->Test->outParm->,[{"inputPropertyA":"0001","inputPropertyB":"11","outputPropertyA":"222"},{"inputPropertyA":"0002","inputPropertyB":"22","outputPropertyA":"333"}]
3 搭建JPA框架
3.1 搭建SpringBoot项目
参考https://www.cnblogs.com/1446358788-qq/p/13972548.html
3.2 相关文件
配置文件:pom依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>jiayou</artifactId> <version>0.0.1-SNAPSHOT</version> <name>jiayou</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <!-- lombok Data/builder等注解 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>1.18.2</version> </dependency> <!-- 用于Table 和 Entity等注解 --> <dependency> <groupId>jakarta.persistence</groupId> <artifactId>jakarta.persistence-api</artifactId> <version>2.2.3</version> <scope>compile</scope> </dependency> <!-- mapStruct注解,类转化,生成实现类 --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.4.2.Final</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.4.2.Final</version> </dependency> <!-- jpa判断为空等 --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.3</version> </dependency> <!-- junit注解,用于测试类 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- 测试类 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.22</version> <scope>test</scope> </dependency> <!-- json打印 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
配置文件:application.properties
#datasource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=***** #jpa?? spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) # ??java???????????????????????????????????????????????????, # ??????update,??????springboot??????????none?ok?? spring.jpa.hibernate.ddl-auto = none # Naming strategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
PO
package com.example.jiayou.ceshi; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Setter @Getter @Table(name = "T_DDWEI") public class TDdwei { /** * 属性A */ @Id @Column(name = "INPUT_PROPERTY_A") private String inputPropertyA; /** * 属性B */ @Column(name = "INPUT_PROPERTY_B") private String inputPropertyB; /** * 属性C */ @Column(name = "OUTPUT_PROPERTY_A") private String outputPropertyA; }
Dao
package com.example.jiayou.ceshi; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface TDdweiDao extends JpaRepository<com.example.jiayou.ceshi.TDdwei,String> { /** * 根据主键查询,最开始用的是findById,后来因为某种原因废弃掉了 * @author weidoudou * @date 2022/8/4 7:52 * @param inputPropertyA 请添加参数描述 * @return com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei **/ com.example.jiayou.ceshi.TDdwei findByInputPropertyA(String inputPropertyA); /** * 分页 ,查询所有数据 * @param specification * @param pageable * @return */ Page<com.example.jiayou.ceshi.TDdwei> findAll(Specification specification, Pageable pageable); /** * 查询列表 * @author weidoudou * @date 2022/8/7 17:31 * @param specification 请添加参数描述 * @return java.util.List<com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei> **/ List<com.example.jiayou.ceshi.TDdwei> findAll(Specification specification); }
Do
package com.example.jiayou.ceshi; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @Builder @NoArgsConstructor public class DdweiEntity { /** * 属性A */ private String inputPropertyA; /** * 属性B */ private String inputPropertyB; /** * 属性C */ private String outputPropertyA; /** * 有参构造方法 * @param inputPropertyA * @param inputPropertyB * @param outputPropertyA */ @Default public DdweiEntity(String inputPropertyA, String inputPropertyB, String outputPropertyA) { this.inputPropertyA = inputPropertyA; this.inputPropertyB = inputPropertyB; this.outputPropertyA = outputPropertyA; } }
Default注解类
package com.example.jiayou.ceshi; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.RUNTIME) public @interface Default { }
Converter
package com.example.jiayou.ceshi; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; /** * 该类主要处理do与po之间的转换 * @author weidoudou * @date 2022/8/4 8:05 **/ @Mapper(componentModel = "spring") public interface DDweiConverter { DDweiConverter INSTANCE = Mappers.getMapper(DDweiConverter.class); /** * do转po * @author weidoudou * @date 2022/8/4 8:08 * @param entity 请添加参数描述 * @return com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei **/ TDdwei toPo(DdweiEntity entity); /** * po转do * @author weidoudou * @date 2022/8/4 8:09 * @param po 请添加参数描述 * @return com.ddwei.domain.moduleA.domainobject.DdweiEntity **/ DdweiEntity toDomainObject(TDdwei po); }
Factory
package com.example.jiayou.ceshi; import org.springframework.context.annotation.Bean; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; public class DDweiFactory { @Bean(name="entityManagerFactory") public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); return sessionFactory; } }
Repository接口
package com.example.jiayou.ceshi; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import java.util.List; public interface DdweiRepository { /** *根据主键查询 * @author weidoudou * @date 2022/2/19 12:50 * @param id 请添加参数描述 * @return com.ddwei.domain.moduleA.domainobject.DdweiEntity **/ DdweiEntity findByInputPropertyA(String id); /** * 保存do * @author weidoudou * @date 2022/2/19 12:50 * @param entity 请添加参数描述 * @return com.ddwei.domain.moduleA.domainobject.DdweiEntity **/ DdweiEntity saveOrUpdate(DdweiEntity entity); /** * 根据do查找dolist * @author weidoudou * @date 2022/8/7 17:35 * @param entity 请添加参数描述 * @return java.util.List<com.ddwei.domain.moduleA.domainobject.DdweiEntity> **/ List<DdweiEntity> findAllList(DdweiEntity entity); /** *分页 ,查询所有数据 * @author weidoudou * @date 2022/8/7 17:29 * @param specification 请添加参数描述 * @param pageable 请添加参数描述 * @return org.springframework.data.domain.Page<com.ddwei.infrastructure.moduleA.dao.jpa.entity.TDdwei> **/ Page<DdweiEntity> findAll(Specification specification, Pageable pageable); }
Repository实现类
package com.example.jiayou.ceshi; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class DdweiRepositoryImpl implements DdweiRepository { @Autowired private TDdweiDao tDdweiDao; @Autowired private DDweiConverter dDweiConverter; @Override public DdweiEntity findByInputPropertyA(String id) { //查询出po TDdwei tDdwei = tDdweiDao.findByInputPropertyA(id); return dDweiConverter.toDomainObject(tDdwei); } @Override public DdweiEntity saveOrUpdate(DdweiEntity entity) { TDdwei tDdwei = dDweiConverter.toPo(entity); return dDweiConverter.toDomainObject(tDdweiDao.saveAndFlush(tDdwei)); } @Override public List<DdweiEntity> findAllList(DdweiEntity entity) { List<TDdwei> list = tDdweiDao.findAll(new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> preList = new ArrayList<>(); if(org.apache.commons.lang.StringUtils.isNotBlank(entity.getInputPropertyA())){ preList.add(criteriaBuilder.equal(root.get("inputPropertyA").as(String.class),entity.getInputPropertyA())); } if(org.apache.commons.lang.StringUtils.isNotBlank(entity.getInputPropertyB())){ preList.add(criteriaBuilder.equal(root.get("inputPropertyB").as(String.class),entity.getInputPropertyB())); } criteriaQuery.where(preList.toArray(new Predicate[preList.size()])); return criteriaQuery.getRestriction(); } }); //判断非空,po转do List<DdweiEntity> entityList = Optional.ofNullable(list).map( listE->{ return listE.stream().map(com.example.jiayou.ceshi.DDweiConverter.INSTANCE::toDomainObject).collect(Collectors.toList()); } ).orElse(new ArrayList<>()); return entityList; } @Override public Page<DdweiEntity> findAll(Specification specification, Pageable pageable) { return null; } }
测试类:
package com.example.jiayou; import com.alibaba.fastjson.JSON; import com.example.jiayou.ceshi.DdweiEntity; import com.example.jiayou.ceshi.DdweiRepository; import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONArray; 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.util.List; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = JiayouApplication.class) public class DdweiRepositoryImplTest { @Autowired DdweiRepository ddweiRepository; @Test public void Test(){ DdweiEntity entity = DdweiEntity.builder().inputPropertyB("11").build(); List<DdweiEntity> entityList = ddweiRepository.findAllList(entity); log.info("DdweiRepositoryImplTest->Test->outParm->,{}", JSON.toJSONString(entityList)); } }
数据库:
测试结果:
2022-08-15 21:10:52.948 INFO 15560 --- [ main] c.e.jiayou.DdweiRepositoryImplTest : DdweiRepositoryImplTest->Test->outParm->,[{"inputPropertyA":"0001","inputPropertyB":"11","outputPropertyA":"222"},{"inputPropertyA":"0003","inputPropertyB":"11","outputPropertyA":"444"}]
诸葛