<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
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
@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;
}
}
/**
* 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;
}
/**
* 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);
}
/**
*
* @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);
}
用到了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);
}
}
/**
* 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);
}
}