Spring Boot + MongoDB Id query - java

I have a Spring Boot application combined with MongoDB as the persistance layer. I have the following structure:
public class Resource {
#Id
public String Id;
...
}
I also have a ResourceRepository:
#RepositoryRestResource(collectionResourceRel = "resources", path = "resources")
public interface ResourceRepository extends MongoRepository<Resource, String> {
Resource findById(#Param("Id")String Id);
}
I found online that a way to have the id property returned in the JSON when you perform a GET request like http://localhost:8080/resources/ is to change the id property to Id (uppercase i). Indeed, if the property is lowercase, I don't get back an id field but if I change it to uppercase then I get it. For a reason, I need to get back the id property so I used the uppercase i. So far, so good.
However, when I tried to execute the query findById included in my repository I get an exception:
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property id found on app.model.Resource!
If I change the Id property to id (lowercase i) I can execute successfully the /resources/search/findById?id=... GET request.
I tried creating a custom controller with a query that finds and returns a Resource based on the id that is given:
#Controller
#RequestMapping("/resource")
public class ResourceController {
#Autowired
MongoOperations mongoOperations;
#RequestMapping(value="/findById/{resourceId}/", method= RequestMethod.GET)
#ResponseBody
public Resource findByResourceId(#PathVariable("resourceId") String resourceId) {
Resource resource = mongoOperations.findOne(query(Criteria.where("Id").is(resourceId)), Resource.class,"DOJ");
}
}
but I receive the same error:
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property id found on app.model.Resource!
Any idea on how to both have the id property displyed in the JSon and be able to findById?

Well, I found the answer myself. Switch back to lowercase id so findById works and add the following class to the project:
#Configuration
public class SpringDataRestConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Resource.class);
}
}
As the name of the method suggests, this configuration makes Resource class objects to expose their ids in JSON.
UPDATE: If you are using the latest or relatively latest version of spring-boot, the RepositoryRestConfigurerAdapter class has been deprecated, and the java-doc suggests to use the interface RepositoryRestConfigurer directly.
So your code should look like this:
#Configuration
public class SpringDataRestConfiguration implements RepositoryRestConfigurer
...

Related

How to retrieve custom annotation fields?

I would like to implement a custom annotation that could be applied to a class (once inside an app), to enable a feature (Access to remote resources). If this annotation is placed on any config class, it will set the access for the whole app. So far it isn't that hard (see example below), but I want to include some definition fields in the #interface that will be used in the access establishing process.
As an example, Spring has something very similar: #EnableJpaRepositories. Access is enabled to the DB, with parameters in the annotation containing definitions. For example: #EnableJpaRepositories(bootstrapMode = BootstrapMode.DEFERRED)
So far, I have:
To create only the access I'm using something like that:
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Import(AccessHandlerConfiguration.class)
public #interface EnableAccessHandlerAutoconfigure {
String name() default "";
}
Using it:
#EnableAccessHandlerAutoconfigure{name="yoni"}
#Configuration
public class config {}
AccessHandlerConfiguration is a configuration class that contains beans that establish the connection.
The problem I'm having is that I don't know how to retrieve the field name's value. What should I do?
Retrieving the value may be accomplished as follows:
this.getClass().getAnnotation(EnableAccessHandlerAutoconfigure.class).name()
To expand on my comment with an actual example configuration class that uses this:
#EnableAccessHandlerAutoconfigure(name="yoni")
#Configuration
public class SomeConfiguration {
#Bean
SomeBean makeSomeBean() {
return new SomeBean(this.getClass().getAnnotation(EnableAccessHandlerAutoconfigure.class).name());
}
}
This is how you get the value of name, as to what you are going to do next, that depends on you.
After a long research, I found a way: There is a method in Spring's ApplicationContext that retrieves bean names according to their annotations getBeanNamesForAnnotation, then get the annotation itself findAnnotationOnBean, and then simply use the field getter.
#Configuration
public class AccessHandlerConfiguration {
private final ApplicationContext applicationContext;
public AccessHandlerConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
String[] beansWithTheAnnotation = applicationContext.getBeanNamesForAnnotation(EnableRabbitAutoconfigure.class);
for (String beanName : beansWithTheAnnotation) {
EnableRabbitAutoconfigure annotationOnBean = applicationContext.findAnnotationOnBean(beanName, EnableRabbitAutoconfigure.class);
System.out.println("**********" + beanName + "*********************" + annotationOnBean.name() + "*******************");
}
}
}
Results:
**********config*********************yoni*******************

Why I get error "No property found" on repository?

I use java spring and mongodb repository for my project.
Here is repository defeniton:
#Repository
public interface InfoRepository extends MongoRepository<Info, String> {
List<InfoDto> findAll();
}
Here is Info Defenition:
#Document("info")
#Data
public class Info{
#Id
private String id = null;
private String name;
private String companyName;
private String email;
private Address address;
private String website;
}
Here is InfoDto class defenition:
#Data
public class InfoDto {
private String name;
private String companyName;
private Address address;
}
When I start to run the project IU get this error:
'findAll()' in '...repository.InfoRepository' clashes with 'findAll()'
in 'org.springframework.data.mongodb.repository.MongoRepository'; attempting to use incompatible return type
To prevent the clashe I change the name of the repository function from this:
List<InfoDto> findAll();
to this:
List<InfoDto> findAllMakeProjection();
But after I make changes above and run the function, I get this error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'infoServiceImpl' defined in file
[...\InfoServiceImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'infoRepository' defined in ".../repository.InfoRepository" defined in #EnableMongoRepositories
declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration:
Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException:
No property findAllMakeProjection found for type Info!
Any idea why I get the error and how to fix it?
List<T> findAll() is a method provided in MongoRepository Interface, so it's not possible to change its return type in sub-interfaces. At most, you can change the return type to List implementations like ArrayList<T> or LinkedList<T>.
If you change the method name to List<InfoDto> findAllMakeProjection(), Spring Data MongoDB will try to build the query using the property name, but there is no property named so it will throw an error.
But it is allowed to add anything before By word in the method name, e.g. findAllBy, findEverythingBy, findDataBy. Anything after By will work as filters(where condition) and if we don't add anything after By, it will work like findAll (no filters)
So, change the method name accordingly and you will be able to run your query.
What happens in here is findAll() is a default built in repository method name reserved for Spring Data JPA. so if you introduce your own findAll() inside your custom Repository(no matter it is JPARespository or MongoRepository ) it will clash with the findAll() provided by JPA.
changing the method name to List<InfoDto> findAllMakeProjection(); will make JPA to build the query using JPQL so it will try to extract entity properties from the method name unless you defined the query with #Query annotation.
So if you want to do so it should be something like findAllBySomeCondition or findBySomeCondition
ex : findByNameAndCompanyName(), findByEmail(), findAllByCompanyName()
Best way is to remove the List<InfoDto> findAll(); inside InfoRepository. Still, you can call
#Autowired
private InfoRepository infoRepository;
.......
infoRepository.findAll();
So this will return a List<Info>.
And simply you cannot reurn a List of DTO objects directly through MongoRepository like you did. It will originally return a List of model objects(List<Info>). in order to return a list of DTOs,
#Repository
public interface InfoRepository extends MongoRepository<Info, String> {
#Query(value="select new com.foo.bar.InfoDto(i.name,i.companyName, i.address) from Info i")
List<InfoDto> findAllInfos();
}
you might need to bit tricky and do additional things with mapping address from entity to DTO.

Cucumber - Share context with the type registry configuration file

What I want: I want to use a spring #Autowired annotation in the file conventionally named "TypeRegistryConfiguration". It works perfectly well for steps file, but for some reason the dependency injection does not work in this file (there is no error/warn message even in debug level). Spring scans "com.funky.steps", which contains the steps, the context and the type registry configuration file, see example below.
Context:
package com.funky.steps.context;
#Component
public class CommonContext {
...
Type registry configuration:
package com.funky.steps.typeregistry;
public class TypeRegistryConfiguration implements TypeRegistryConfigurer {
#Autowired
private CommonContext context; // NOT INJECTED !
#Override
public Locale locale() {
return Locale.ENGLISH;
}
#Override
public void configureTypeRegistry(TypeRegistry typeRegistry) {
registerStuff(typeRegistry)
}
...
Steps:
package com.funky.steps;
public class WebServiceSteps {
#Autowired
private CommonContext context; // Correctly injected
...
Why I want it: I have steps that save variables in the context for later use. When I build an object using type registry, I want to be able to access these variables. Example:
Given I call the web service 1
And the response field "id" will be used as "$id" # id is saved in the context
When I call the web service 2: # call type registry configuration to build the request using $id (which I can not access because it is in the context and #Autowired is not working)
| id | $id |
Then ...
This is not possible in Cucumber 4.x but you are able to register parameter and data table types as part of the glue in Cucumber 5.0.0-RC1.
Instead of registering a parameter type with registry.registerParameterType you'd use #ParameterType instead. The same works for the data table types.
private final Catalog catalog;
private final Basket basket;
#ParameterType("[a-z ]+")
public Catalog catalog(String name) {
return catalogs.findCatalogByName(name);
}
#ParameterType("[a-z ]+")
public Product product(String name) {
return catalog.findProductByName(name);
}
#Given("the {catalog} catalog")
public void the_catalog(Catalog catalog){
this.catalog = catalog
}
#When("a user places the {product} in his basket")
public void a_user_place_the_product_in_his_basket(Product product){
basket.add(product);
}
Note: The method name is used as the parameter name. A parameter name can also be provided via the name property of #ParameterType.
See: https://cucumber.io/blog/announcing-cucumber-jvm-v5-0-0-rc1/
What ever you are looking for can be achieve by cucumber 5, using qaf-cucumber and cucumber 5 using qaf-cucumber by using .
below is example:
Given I call the web service 1
And the response field "id" will be used as "id"
When I call the web service 2:
| id | ${id} |
Then ...
Step implementation may look like store method implementation:
#And("the response field {sting} will be used as {string}")
public void theResponseFiFeldWillBeUsedAs(String field, String key) {
//do the need full
String value = read(field);
getBundle().setProperty(key, value);
}
##QAFTestStep("I call the web service 2:")
public void iCallWS2:(Map<String, Object> map) {
//map should be with key id and resolved value
}
Furthermore you can get benefit from web-service support library as well. It offers request call repository concept with parameter which makes web service testing easy and maintainable.
What I want is impossible for now. See :
https://github.com/cucumber/cucumber-jvm/issues/1516

Use Date type in the graphql scheme

I want to introduce a scalar type to the graphql scheme and provide resolver for it.
I believe what I need to do is to provide the corresponding resolver for the new type as described here
I use spring boot starter to implement the server.
com.graphql-java:graphql-spring-boot-starter:5.0.2
There is schema.graphqls:
type Query {
pets(last: Int): [Pet]
}
type Pet {
id: ID
name: String
}
and QueryResolver:
#Component
public class Query implements GraphQLQueryResolver {
#Autowired
PetStore petStore;
public Pet pet(long id) {
return petStore.pet(id);
}
public List<Pet> pets(Integer last) {
return petStore.pets().stream()
.limit(last != null ? last : Integer.MAX_VALUE)
.collect(Collectors.toList());
}
}
I believe that there is a way to update a scheme like this:
type Pet {
id: ID
name: String
dateOfBirth: LocalDateTime
}
scalar LocalDateTime
and provide resolver to define how new field value should be processed, like this:
#Component
public class DateResolver extends GraphQLScalarType {
// serialize/deserialize logic
}
Unfochinatly I get following exception:
com.coxautodev.graphql.tools.SchemaClassScannerError: Expected a user-defined GraphQL scalar type with name 'LocalDateTime' but found none!
After some research, I found resolvers for the java types in the graphql-java-9.2.jar!/graphql/Scalars.class and inspired of it.
Not sure what your setup looks like but for me this is how I quickly resolved that exception:
I extended the GraphQlHttpServlet and there is where I load my graphql schema (overriding the getConfiguration() method etc to start the servlet... sorry I can't go into much detail but I'm sure looking at the docs will make what I just said make sense). In getConfiguration() I have:
return GraphQLConfiguration.with(createSchema())
.with(customGraphQLContextBuilder)
.build();
and in createSchema I load the graphql schema and I PARSE it:
.
.
return SchemaParser.newParser()
.schemaString(schemaString)
.scalars(CustomDateTimeScalar.getDateTimeScalar())
.resolvers(myQueryResolverXYZ)
.build()
.makeExecutableSchema();
.
.
Just in case this sheds light on someone else that runs into this.

How to set tableName dynamically using environment variable in spring boot?

I am using AWS ECS to host my application and using DynamoDB for all database operations. So I'll have same database with different table names for different environments. Such as "dev_users" (for Dev env), "test_users" (for Test env), etc.. (This is how our company uses same Dynamo account for different environments)
So I would like to change the "tableName" of the model class using the environment variable passed through "AWS ECS task definition" environment parameters.
For Example.
My Model Class is:
#DynamoDBTable(tableName = "dev_users")
public class User {
Now I need to replace the "dev" with "test" when I deploy my container in test environment. I know I can use
#Value("${DOCKER_ENV:dev}")
to access environment variables. But I'm not sure how to use variables outside the class. Is there any way that I can use the docker env variable to select my table prefix?
My Intent is to use like this:
I know this not possible like this. But is there any other way or work around for this?
Edit 1:
I am working on the Rahul's answer and facing some issues. Before writing the issues, I'll explain the process I followed.
Process:
I have created the beans in my config class (com.myapp.users.config).
As I don't have repositories, I have given my Model class package name as "basePackage" path. (Please check the image)
For 1) I have replaced the "table name over-rider bean injection" to avoid the error.
For 2) I printed the name that is passing on to this method. But it is Null. So checking all the possible ways to pass the value here.
Check the image for error:
I haven't changed anything in my user model class as beans will replace the name of the DynamoDBTable when the beans got executed. But the table name over riding is happening. Data is pulling from the table name given at the Model Class level only.
What I am missing here?
The table names can be altered via an altered DynamoDBMapperConfig bean.
For your case where you have to Prefix each table with a literal, you can add the bean as such. Here the prefix can be the environment name in your case.
#Bean
public TableNameOverride tableNameOverrider() {
String prefix = ... // Use #Value to inject values via Spring or use any logic to define the table prefix
return TableNameOverride.withTableNamePrefix(prefix);
}
For more details check out the complete details here:
https://github.com/derjust/spring-data-dynamodb/wiki/Alter-table-name-during-runtime
I am able to achieve table names prefixed with active profile name.
First added TableNameResolver class as below,
#Component
public class TableNameResolver extends DynamoDBMapperConfig.DefaultTableNameResolver {
private String envProfile;
public TableNameResolver() {}
public TableNameResolver(String envProfile) {
this.envProfile=envProfile;
}
#Override
public String getTableName(Class<?> clazz, DynamoDBMapperConfig config) {
String stageName = envProfile.concat("_");
String rawTableName = super.getTableName(clazz, config);
return stageName.concat(rawTableName);
}
}
Then i setup DynamoDBMapper bean as below,
#Bean
#Primary
public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB amazonDynamoDB) {
DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDB,new DynamoDBMapperConfig.Builder().withTableNameResolver(new TableNameResolver(envProfile)).build());
return mapper;
}
Added variable envProfile which is an active profile property value accessed from application.properties file.
#Value("${spring.profiles.active}")
private String envProfile;
We have the same issue with regards to the need to change table names during runtime. We are using Spring-data-dynamodb 5.0.2 and the following configuration seems to provide the solutions that we need.
First I annotated my bean accessor
#EnableDynamoDBRepositories(dynamoDBMapperConfigRef = "getDynamoDBMapperConfig", basePackages = "my.company.base.package")
I also setup an environment variable called ENV_PREFIX which is Spring wired via SpEL.
#Value("#{systemProperties['ENV_PREFIX']}")
private String envPrefix;
Then I setup a TableNameOverride bean:
#Bean
public DynamoDBMapperConfig.TableNameOverride getTableNameOverride() {
return DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(envPrefix);
}
Finally, I setup the DynamoDBMapperConfig bean using TableNameOverride injection. In 5.0.2, we had to setup a standard DynamoDBTypeConverterFactory in the DynamoDBMapperConfig builder to avoid NPE.:
#Bean
public DynamoDBMapperConfig getDynamoDBMapperConfig(DynamoDBMapperConfig.TableNameOverride tableNameOverride) {
DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder();
builder.setTableNameOverride(tableNameOverride);
builder.setTypeConverterFactory(DynamoDBTypeConverterFactory.standard());
return builder.build();
}
In hind sight, I could have setup a DynamoDBTypeConverterFactory bean that returns a standard DynamoDBTypeConverterFactory and inject that into the getDynamoDBMapperConfig() method using the DynamoDBMapperConfig builder. But this will also do the job.
I up voted the other answer but here is an idea:
Create a base class with all your user details:
#MappedSuperclass
public abstract class AbstractUser {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
Create 2 implentations with different table names and spirng profiles:
#Profile(value= {"dev","default"})
#Entity(name = "dev_user")
public class DevUser extends AbstractUser {
}
#Profile(value= {"prod"})
#Entity(name = "prod_user")
public class ProdUser extends AbstractUser {
}
Create a single JPA respository that uses the mapped super classs
public interface UserRepository extends CrudRepository<AbstractUser, Long> {
}
Then switch the implentation with the spring profile
#RunWith(SpringJUnit4ClassRunner.class)
#DataJpaTest
#Transactional
public class UserRepositoryTest {
#Autowired
protected DataSource dataSource;
#BeforeClass
public static void setUp() {
System.setProperty("spring.profiles.active", "prod");
}
#Test
public void test1() throws Exception {
DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
ResultSet tables = metaData.getTables(null, null, "PROD_USER", new String[] { "TABLE" });
tables.next();
assertEquals("PROD_USER", tables.getString("TABLE_NAME"));
}
}

Categories