Java 类org.springframework.data.repository.CrudRepository 实例源码

项目:document-management-store-app    文件:PermissionEvaluatorImpl.java   
@Override
public boolean hasPermission(@NotNull Authentication authentication,
                             @NotNull Serializable serializable,
                             @NotNull String className,
                             @NotNull Object permissions) {
    boolean result = false;
    CrudRepository<Object, Serializable> repository = repositoryFinder.find(className);
    if (repository != null) {
        Object targetDomainObject = repository.findOne(serializable);
        if (targetDomainObject instanceof CreatorAware) {
            result = hasPermission(authentication, targetDomainObject, permissions);
        } else if (targetDomainObject == null) {
            result = true;
        }
    }
    return result;
}
项目:d-kom-collaborative    文件:ServiceStepDefinitions.java   
@Then("^the database will be empty$")
public void the_database_will_be_empty() throws Throwable {
    ClosureService closureService = getBean(ClosureService.class);
    Map<String, CrudRepository> crudRepositories = getBeansOfType(CrudRepository.class);

    for (final Map.Entry<String, CrudRepository> repository : crudRepositories.entrySet()) {
        Closure checkEmpty = new Closure() {
            @Override
            public void execute() throws Exception {
                long entityCount = repository.getValue().count();
                String message = format("%s must be empty but is %s", repository.getKey(), entityCount);
                assertThat(message, entityCount, is(EMPTY));
            }
        };
        closureService.execute(checkEmpty);
    }

}
项目:mysql-binlog-replicator    文件:MySQLEventListenerTest.java   
public void setUpDomainClassAnalyzer(CrudRepository crudRepository, User user) throws ReflectiveOperationException {
    Map<String, DomainClass> domainMap = new HashMap<>();
    List<String> tablesExpected = new ArrayList<>();
    tablesExpected.add("user");
    DomainClass domainClass = new DomainClass();
    domainClass.setDomainClass(User.class);
    domainClass.setCrudRepository(crudRepository);
    OneToOneRequester cartSQLRequester = new OneToOneRequester();
    cartSQLRequester.setAssociatedField(User.class.getDeclaredField("cart"));
    Map<String, SQLRequester> sqlRequesterMap = new HashMap<>();
    sqlRequesterMap.put("cart", cartSQLRequester);
    domainClass.setSqlRequesters(sqlRequesterMap);
    domainMap.put("user", domainClass);
    when(domainClassAnalyzer.getDomainClassMap()).thenReturn(domainMap);
    when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(tablesExpected);
    doReturn(user).when(domainClassAnalyzer).generateInstanceFromName("user");
}
项目:richobjects    文件:RichObjectRepositoryImpl.java   
public RichObjectRepositoryImpl(
        Class<RichObjectType> domainClass,
        Class<RichObjectImplementation> implementationClass,
        Class<EntityType> entityType,
        CrudRepository<EntityType, ID> entityRepository,
        final ApplicationContext applicationContext) {

    this.domainClass = domainClass;
    this.entityRepository = entityRepository;
    this.applicationContext = applicationContext;

    try {
        entityField = findEntityField(implementationClass, entityType);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw propagate(e);
    }

}
项目:document-management-store-app    文件:RepositoryFinder.java   
public CrudRepository<Object, Serializable> find(@NotNull String domainClassName) {
    try {
        return this.find(Class.forName(domainClassName));
    } catch (ClassNotFoundException e) {
        throw new RepositoryCouldNotBeFoundException("Could not find a Repository for Domain class: " + domainClassName);
    }
}
项目:document-management-store-app    文件:RepositoryFinder.java   
@SuppressWarnings(value = "unchecked")
public CrudRepository<Object, Serializable> find(@NotNull Class<?> domainClass) {
    Repositories repositories = new Repositories(listableBeanFactory);

    Iterator<Class<?>> it = repositories.iterator();
    while (it.hasNext()) {
        Object repository = repositories.getRepositoryFor(domainClass);
        if (repository != null && repository instanceof CrudRepository) {
            return (CrudRepository<Object, Serializable>)repository;
        }
    }

    return null;
}
项目:spring-data-examples    文件:AdvancedSolrRepositoryTests.java   
@Override
protected void doInitTestData(CrudRepository<Product, String> repository) {

    Product playstation = Product.builder().id("id-1").name("Playstation")
            .description("The Sony playstation was the top selling gaming system in 1994.").popularity(5).build();
    Product playstation2 = Product.builder().id("id-2").name("Playstation Two")
            .description("Playstation two is the successor of playstation in 2000.").build();
    Product superNES = Product.builder().id("id-3").name("Super Nintendo").popularity(3).build();
    Product nintendo64 = Product.builder().id("id-4").name("N64").description("Nintendo 64").popularity(2).build();

    repository.save(Arrays.asList(playstation, playstation2, superNES, nintendo64));
}
项目:interview-preparation    文件:DBCountRunner.java   
@Override
public void run(String... arg0) throws Exception {

    for (final CrudRepository cr : repositories) {
        System.err.println(getRepositoryName(cr.getClass()) + " has  " + cr.count() + ". <<DBCountRunner>>");
    }

}
项目:jeet    文件:BatchImportHandler.java   
@Override
public void dataImport(ApplicationContext applicationContext, Map<String, List<Serializable>> importData) {
    for (Entry<String, List<Serializable>> entry : importData.entrySet()) {

        @SuppressWarnings("unchecked")
        CrudRepository<Serializable, Serializable> crudDao = applicationContext.getBean(entry.getKey(), CrudRepository.class);

        crudDao.save(entry.getValue());
    }
}
项目:openlmis-stockmanagement    文件:BaseCrudRepositoryIntegrationTest.java   
@Test
public void shouldCreate() throws Exception {
  CrudRepository<T, UUID> repository = this.getRepository();

  T instance = this.generateInstance();
  Assert.assertNull(instance.getId());

  instance = repository.save(instance);
  assertInstance(instance);

  Assert.assertTrue(repository.exists(instance.getId()));
}
项目:openlmis-stockmanagement    文件:BaseCrudRepositoryIntegrationTest.java   
@Test
public void shouldFindOne() throws Exception {
  CrudRepository<T, UUID> repository = this.getRepository();

  T instance = this.generateInstance();

  instance = repository.save(instance);
  assertInstance(instance);

  UUID id = instance.getId();

  instance = repository.findOne(id);
  assertInstance(instance);
  Assert.assertEquals(id, instance.getId());
}
项目:openlmis-stockmanagement    文件:BaseCrudRepositoryIntegrationTest.java   
@Test
public void shouldDelete() throws Exception {
  CrudRepository<T, UUID> repository = this.getRepository();

  T instance = this.generateInstance();
  assertNotNull(instance);

  instance = repository.save(instance);
  assertInstance(instance);

  UUID id = instance.getId();

  repository.delete(id);
  Assert.assertFalse(repository.exists(id));
}
项目:openlmis-template-service    文件:AuditLogInitializer.java   
/**
 * This method is part of CommandLineRunner and is called automatically by Spring.
 * @param args Main method arguments.
 */
public void run(String... args) {
  //Get all JaVers repositories.
  Map<String,Object> repositoryMap =
          applicationContext.getBeansWithAnnotation(JaversSpringDataAuditable.class);

  //For each one...
  for (Object object : repositoryMap.values()) {
    if (object instanceof PagingAndSortingRepository) {
      createSnapshots((PagingAndSortingRepository<?, ?>) object);
    } else if (object instanceof CrudRepository) {
      createSnapshots((CrudRepository<?, ?>) object);
    }
  }
}
项目:wonderjameeee    文件:ContentManagementService.java   
private <T extends ContentEntity> T safeGet(ContentDto s, CrudRepository<? extends T, UUID> repo, T newEntity) {
    try {
        T entity = repo.findOne(s.getId());
        return entity;
    } catch (Exception e) {
        return newEntity;
    }
}
项目:putput    文件:ContactService.java   
private <T extends BaseEntity, U> void updateCollection(Collection<T> currentValues,
                                                     Collection<U> updatedValues,
                                                     Supplier<T> newInstance,
                                                     Function<U, String> idFun,
                                                     Function<U, Function<T, T>> updateFunctionSupplier,
                                                     CrudRepository<T, String> repository) {
  Map<String, List<T>> valuesMap = currentValues.stream()
      .collect(Collectors.groupingBy(T::getId));

  List<String> newIds = updatedValues
      .stream()
      .map(newCollectionItem -> {
        Optional<T> existingItem = ofNullable(valuesMap.get(idFun.apply(newCollectionItem)))
            .flatMap(toFirst());

        if (existingItem.isPresent()) {
          return repository.save(updateFunctionSupplier.apply(newCollectionItem).apply(existingItem.get()));
        } else {
          T newItem = newInstance.get();
          repository.save(updateFunctionSupplier.apply(newCollectionItem).apply(newItem));
          currentValues.add(newItem);
          return newItem;
        }
      })
      .map(T::getId)
      .collect(Collectors.toList());

  currentValues
      .stream()
      .filter(notIn(newIds))
      .collect(Collectors.toList())
      .forEach(removeFrom(currentValues, repository));    
}
项目:yona-server    文件:BaseSpringIntegrationTest.java   
@Before
public final void setUpPerTestBase()
{
    MockitoAnnotations.initMocks(this);

    Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>();
    repositoriesMap.put(User.class, userRepository);
    repositoriesMap.put(UserAnonymized.class, userAnonymizedRepository);
    repositoriesMap.putAll(getRepositories());
    Set<CrudRepository<?, ?>> crudRepositories = filterForCrudRepositories(repositoriesMap.values());
    crudRepositories.forEach(CrudRepository::deleteAll);
    crudRepositories.stream().filter(this::isMock).forEach(r -> JUnitUtil.setUpRepositoryMock(r));
    JUnitUtil.setUpRepositoryProviderMock(repositoriesMap);
}
项目:yona-server    文件:JUnitUtil.java   
@SuppressWarnings("unchecked")
public static <T, ID extends Serializable> void setUpRepositoryMock(CrudRepository<T, ID> mockRepository)
{
    // save should not return null but the saved entity
    when(mockRepository.save(Matchers.<T> any())).thenAnswer(new Answer<T>() {
        @Override
        public T answer(InvocationOnMock invocation) throws Throwable
        {
            Object[] args = invocation.getArguments();
            return (T) args[0];
        }
    });

}
项目:mongo-rest    文件:ApplicationRegistry.java   
@Override
public void handleBeanEntry(Object bean, String documentType) {
    log.info("Mapping '" + documentType + "' to bean '" + bean.getClass().getCanonicalName() + "'");
    if (bean instanceof CrudRepository) {
        crudRepositoryRegistry.put(documentType, (CrudRepository<? extends BaseDocument, String>) bean);
    } else if (bean instanceof CrudService) {
        crudServiceRegistry.put(documentType, (CrudService<? extends BaseDocument>) bean);
    } else if (bean instanceof PersistenceListenerManager) {
        persistenceListenerManagerRegistry.put(documentType, (PersistenceListenerManager<? extends BaseDocument>) bean);
    }
}
项目:mongo-rest    文件:ApplicationRegistry.java   
public CrudRepository<? extends BaseDocument, String> getCrudRepository(Class clazz) {
    String documentType = getDocumentType(clazz);
    if (clazz != null) {
        return getCrudRepository(documentType);
    }
    else return null;
}
项目:mongo-rest    文件:DocumentValidationTest.java   
@PostConstruct
public void init() {
    String documentType = applicationRegistry.getDocumentType((Class) type);
    this.repository = (CrudRepository<T, String>) applicationRegistry.getCrudRepository((Class) type);
    this.service = (CrudService<T>) applicationRegistry.getCrudService((Class) type);
    this.documentProvider = (DocumentProvider<T>) testRegistry.getDocumentBuilder(documentType);

    log.info("Initializing TimeProvider mocks...");
    EasyMock.resetToNice(service.getTimeProvider());
    EasyMock.expect(service.getTimeProvider().getSystemTimeMillis()).andStubReturn(1000L);
}
项目:cloudbreak    文件:AbstractCloudPersisterService.java   
private Class getEntityClassForRepository(CrudRepository repo) {
    Class<?> originalInterface = repo.getClass().getInterfaces()[0];
    EntityType annotation = originalInterface.getAnnotation(EntityType.class);
    if (annotation == null) {
        throw new IllegalStateException("Entity class is not specified for repository: " + originalInterface.getSimpleName());
    }
    return annotation.entityClass();
}
项目:spring-music    文件:AlbumRepositoryPopulator.java   
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (event.getApplicationContext().equals(applicationContext)) {
        CrudRepository albumRepository =
                BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, CrudRepository.class);

        if (albumRepository != null && albumRepository.count() == 0) {
            populate(albumRepository);
        }
    }

}
项目:spring-music    文件:AlbumRepositoryPopulator.java   
@SuppressWarnings("unchecked")
public void populate(CrudRepository repository) {
    Object entity = getEntityFromResource(sourceData);

    if (entity instanceof Collection) {
        for (Album album : (Collection<Album>) entity) {
            if (album != null) {
                repository.save(album);
            }
        }
    } else {
        repository.save(entity);
    }
}
项目:javers    文件:AbstractSpringAuditableRepositoryAspect.java   
private Optional<Class> getRepositoryInterface(JoinPoint pjp) {
    for (Class i : pjp.getTarget().getClass().getInterfaces()) {
        if (i.isAnnotationPresent(JaversSpringDataAuditable.class) && CrudRepository.class.isAssignableFrom(i)) {
            return Optional.of(i);
        }
    }
    return Optional.empty();
}
项目:projectindoorweb    文件:RepositoryRegistry.java   
public static void registerRepository(String name, CrudRepository repository) {
    if (repositoryMap == null) {
        throw new IllegalStateException("Repository registry was not initialized.");
    }
    repositoryMap.putIfAbsent(name, repository);
}
项目:projectindoorweb    文件:RepositoryRegistry.java   
public static CrudRepository getRepositoryByEntityName(String entitiyName) {
    if (repositoryMap == null) {
        throw new IllegalStateException("Repository registry was not initialized.");
    }
    return repositoryMap.get(entitiyName);
}
项目:microservices-tcc-alfa    文件:ClienteService.java   
@Override
protected CrudRepository<Cliente, Long> getCrudRepository() {
    return clienteRepository;
}
项目:microservices-tcc-alfa    文件:PedidoService.java   
@Override
protected CrudRepository<Pedido, Long> getCrudRepository() {
    return pedidoRepository;
}
项目:microservices-tcc-alfa    文件:ProdutoService.java   
@Override
protected CrudRepository<Produto, Long> getCrudRepository() {
    return produtoRepository;
}
项目:spring-data-examples    文件:SolrTestConfiguration.java   
protected void doInitTestData(CrudRepository<Product, String> repository) {

        IntStream.range(0, 100)
                .forEach(index -> repository.save(Product.builder().id("p-" + index).name("foobar").build()));
    }
项目:gauravbytes    文件:ProductService.java   
@Override
public CrudRepository<Product, String> getRepository() {
    return this.productRepository;
}
项目:gauravbytes    文件:UserService.java   
@Override
public CrudRepository<User, String> getRepository() {
    return this.userRepository;
}
项目:gauravbytes    文件:RatingService.java   
@Override
public CrudRepository<Rating, Long> getRepository() {
    return this.ratingRepository;
}
项目:iotplatform    文件:JpaCustomerDao.java   
@Override
protected CrudRepository<CustomerEntity, String> getCrudRepository() {
    return customerRepository;
}
项目:iotplatform    文件:JpaBasePluginDao.java   
@Override
protected CrudRepository<PluginMetaDataEntity, String> getCrudRepository() {
    return pluginMetaDataRepository;
}
项目:iotplatform    文件:JpaDashboardDao.java   
@Override
protected CrudRepository<DashboardEntity, String> getCrudRepository() {
    return dashboardRepository;
}
项目:iotplatform    文件:JpaDashboardInfoDao.java   
@Override
protected CrudRepository getCrudRepository() {
    return dashboardInfoRepository;
}
项目:iotplatform    文件:JpaDeviceCredentialsDao.java   
@Override
protected CrudRepository<DeviceCredentialsEntity, String> getCrudRepository() {
    return deviceCredentialsRepository;
}
项目:iotplatform    文件:JpaDeviceDao.java   
@Override
protected CrudRepository<DeviceEntity, String> getCrudRepository() {
  return deviceRepository;
}
项目:iotplatform    文件:JpaUserCredentialsDao.java   
@Override
protected CrudRepository<UserCredentialsEntity, String> getCrudRepository() {
    return userCredentialsRepository;
}