springboot + spring Data JPA 后端开发流程

JPA Specification

  • 1. 引入JPA的maven依赖
  • 2. 建立springboot分模块项目工程
  • 3. web模块下的resource文件夹下编写application.yml配置文件
  • 4. 在web模块新建config文件夹编写FaceBookDataSourceConfig和DataSourceDev数据源配置
  • 5. 在model模块新建dao文件夹编写Entity实体类
  • 6. 在model模块dao文件夹下编写repository接口
  • 7. 在service模块下编写service接口
    • 7.1 编写通用抽象接口
    • 7.2 新建userService文件夹具体实现业务处理userService
  • 8. 在web模块新建controller文件夹下编写UserController

1. 引入JPA的maven依赖

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>

2. 建立springboot分模块项目工程

不会分模块建工程的可以去网上找一找
springboot + spring Data JPA 后端开发流程_第1张图片

3. web模块下的resource文件夹下编写application.yml配置文件

spring:
  jpa:
    show-sql: true
  datasource:
    # faceBook
    faceBook:
      url: jdbc:mysql://localhost:3306/facebook?useUnicode=true&characterEncoding=utf-8
      username: root
      password: 123456
      driverClassName: com.mysql.jdbc.Driver

4. 在web模块新建config文件夹编写FaceBookDataSourceConfig和DataSourceDev数据源配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryFaceBook",
        transactionManagerRef = "transactionManagerFaceBook",
        basePackages = {"com.xxxxxxxx.dao.facebook"}) //设置Repository所在位置
public class FaceBookDataSourceConfig {

    @Bean(name = "entityManagerFactoryFaceBook")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            @Qualifier("faceBookDataSource") DataSource algDataSource,
            EntityManagerFactoryBuilder factoryBuilder,
            JpaProperties properties) {

        return factoryBuilder.dataSource(algDataSource)
                .packages("com.xxxxxxxx.dao.facebook")
                .properties(properties.getHibernateProperties(new HibernateSettings()))
                .persistenceUnit("faceBookPersistenceUnit")
                .build();
    }

    @Bean(name = "transactionManagerFaceBook")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactoryFaceBook") EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}

/**
 * DataSourceDev
 *
 * @author yhzhao
 * @date 2020/7/14.
 */
@Profile({"dev","test"})
@Configuration
public class DataSourceConfigDev {

    @Value("${spring.datasource.face-book.url}")
    private String faceBookUrl;
    @Value("${spring.datasource.face-book.username}")
    private String faceBookUsername;
    @Value("${spring.datasource.face-book.password}")
    private String faceBookPassword;
    @Value("${spring.datasource.face-book.driver-class-name}")
    private String faceBookDriver;

    /**
     * facebook 数据源
     *
     * @return
     */
    @Bean(name = "faceBookDataSource")
    public DataSource fackBookDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(faceBookUrl);
        dataSource.setUsername(faceBookUsername);
        dataSource.setPassword(faceBookPassword);
        dataSource.setDriverClassName(faceBookDriver);
        return dataSource;
    }
}

5. 在model模块新建dao文件夹编写Entity实体类

/**
 * UserEntity
 *
 * @author yhzhao
 * @date 2020/7/14.
 */
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user",
        indexes = {
                @Index(columnList = "appName, secretUserId", unique = true, name = "idx_secretUserId_appName"),
                @Index(columnList = "userId", name = "idx_userId")})
public class UserEntity extends VersioningBaseEntity {

    /**
     * AppName
     */
    @Column(columnDefinition = "varchar(64) comment '租户名'")
    private String appName;
    /**
     * userId
     */
    @Column(columnDefinition = "varchar(128) comment '用户id'")
    private String userId;

    /**
     * secretUserId
     */
    @Column(columnDefinition = "varchar(128) comment '用户转换id'")
    private String secretUserId;
    /**
     * userInfo
     */
    @Column(columnDefinition = "varchar(512) comment '用户JSON'")
    private String userInfo;

}

6. 在model模块dao文件夹下编写repository接口

/**
 * UserRepository
 *
 * @author yhzhao
 * @date 2020/7/14.
 */
public interface UserRepository extends JpaSpecificationExecutor<UserEntity>, PagingAndSortingRepository<UserEntity, Long> {

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    @Modifying
    @Query("update UserEntity set deleted = 1 where id=:id")
    void deleteById(@Param("id") Long id);
}

7. 在service模块下编写service接口

7.1 编写通用抽象接口

/**
 * 
 * @author yhzhao
 * @date 2020/7/14.
 */
public interface AbstractService {

    JSONResult select(Map<String, Object> params);

    JSONResult insert(Map<String, Object> params);

    JSONResult update(Map<String, Object> params);

    JSONResult delete(Map<String, Object> params);


}

7.2 新建userService文件夹具体实现业务处理userService

用到了JPA的repository和specification实现CRUD操作,可以参照我的上一篇文章开发过程中JPA Specification的应用

/**
 * UserService
 *
 * @author yhzhao
 * @date 2020/7/14.
 */
@Slf4j
@Service
public class UserService implements AbstractService {

    @Autowired
    private UserRepository userRepository;


    @Override
    @Profiled
    public JSONResult select(Map<String, Object> params) {
        List<Map<String, Object>> list = new ArrayList<>();

        UserEntity entity = GsonUtils.fromJson(GsonUtils.toJson(params), UserEntity.class);

        Specification<UserEntity> specification = (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();

            if (!StringUtils.isEmpty(entity.getAppName())) {
                predicateList.add(cb.equal(root.get("appName"), entity.getAppName()));
            }
            if (!StringUtils.isEmpty(entity.getUserId())) {
                predicateList.add(cb.like(root.get("userId"), entity.getUserId() + "%"));
            }
            if (!StringUtils.isEmpty(entity.getSecretUserId())) {
                predicateList.add(cb.like(root.get("secretUserId"), entity.getSecretUserId() + "%"));
            }
            if (!StringUtils.isEmpty(entity.getDeleted())) {
                predicateList.add(cb.equal(root.get("deleted"), entity.getDeleted()));
            }

            return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
        };

        int pageNum = (int) params.get("pageNum");
        int pageSize = (int) params.get("pageSize");
        Page<UserEntity> page = userRepository.findAll(specification, PageRequest.of(pageNum - 1, pageSize
//                new Sort(Sort.Direction.ASC, "appName", "deleted")
        ));

        for (UserEntity content : page.getContent()) {
            list.add(GsonUtils.fromJson(GsonUtils.toJson(content), new TypeToken<Map<String, Object>>() {
            }.getType()));
        }
        return JSONResult.ok(list, page.getTotalElements());
    }

    @Override
    @Profiled
    public JSONResult insert(Map<String, Object> params) {
//        UserEntity entity = GsonUtils.fromJson(GsonUtils.toJson(params), UserEntity.class);
//        userRepository.save(entity);
        return JSONResult.ok(1);
    }

    @Override
    @Profiled
    public JSONResult update(Map<String, Object> params) {
//        UserEntity entity = GsonUtils.fromJson(GsonUtils.toJson(params), UserEntity.class);
//        userRepository.save(entity);
        return JSONResult.ok(1);
    }

    @Override
    @Profiled
    public JSONResult delete(Map<String, Object> params) {
//        UserEntity entity = GsonUtils.fromJson(GsonUtils.toJson(params), UserEntity.class);
//        userRepository.deleteById(entity.getId());
        return JSONResult.ok(1);
    }
}

8. 在web模块新建controller文件夹下编写UserController

/**
 * UserController
 *
 * @author yhzhao
 * @date 2020/7/14.
 */
@RequestMapping("/api/user")
@RestController
public class UserController implements AbstractService {

    @Autowired
    private UserService userService;


    @RequestMapping("/user/select")
    @Override
    @Profiled
    public JSONResult select(@RequestBody Map<String, Object> params) {
        return userService.select(params);
    }

    @RequestMapping("/user/insert")

    @Override
    @Profiled
    public JSONResult insert(@RequestBody Map<String, Object> params) {
        return userService.insert(params);
    }

    @RequestMapping("/user/update")

    @Override
    @Profiled
    public JSONResult update(@RequestBody Map<String, Object> params) {
        return userService.update(params);
    }

    @RequestMapping("/user/delete")

    @Override
    @Profiled
    public JSONResult delete(@RequestBody Map<String, Object> params) {
        return userService.delete(params);
    }
}

你可能感兴趣的:(Java,Java项目开发,java)