I want to get the item with the highest year and has a particular personal name. I'm trying this:
Foo findTopByOrderByYearDesc();
This work great, the problem is when I add a new param to filter results
Foo findTopByOrderByYearDescAndPersonName(#Param("person.name") final String name);
But I get this error:
No property andPersonName found for type Foo!
I try this too but I get de same error:
Foo findTopByOrderByYearDescByPersonName(#Param("person.name") final String name);
You should use the following:
Foo findTopByPersonNameOrderByYearDesc(#Param("person.name") final String name);
The first 'by' keyqord works as a delimiter see here
Related
i got an error after submit my set to database like this
java.lang.String cannot be cast to java.lang.Integer
And, i dont have no idea about to parse this List to integer
carFamilySelectList = new ArrayList<SelectItem>();
List<CarFamily> carFamilyList = carFamilyServiceImpl.selectCarFamilyIdList();
carFamilySelectList.add(new SelectItem("", "Select one"));
for(CarFamily as : carFamilyList) {
carFamilySelectList.add(new SelectItem(as.getCarFamilyId(), as.getCarFamilyName()));
}
Please help!
It's hard to say for sure without what line of code in the database(?) is throwing the exception but my guess is that the cause is that first list entry that's causing the problem:
carFamilySelectList.add(new SelectItem("", "Select one"));
I'm assuming that CarFamily.getCarFamilyId() returns an int, and that the return value of SelectItem.getValue() is being cast to an Integer somewhere? That first list entry is a SelectItem with an empty string as its value. Try using 0 (or -1 or whatever) instead:
carFamilySelectList.add(new SelectItem(0, "Select one"));
But in the future, include more relevant information in your question (the line where the exception is thrown and at least the signatures for the methods in your custom class that are relevant to your question... like getCarFamilyId() in this case).
I'm writing a simple skill similart to the java airplane facts sample and I have two strange behaviours:
1) the same code in one intent works correctly, but in another causes an error;
2) I can't remove an element from a public static List!
I will try to explain better with a very close example.
I have two Intents that we can call:
- ActionIntent;
- StopIntent.
The first intent retrieves a list (of type List) retrieved from a class Constants and returns an attribute of a random CustomObject --
this works correctly.
Then it should set the object to Session Attributes and remove it from the list, because the next time the response should be a second attribute of the last CustomObject plus the first attribute of the new CustomObject. Does it make sense?
Here is the code:
// this row works correctly on the other intent
Map<String, Object> sessionAttributes = input.getAttributesManager().getSessionAttributes();
CustomObject last=(sessionAttributes.get("last")!=null) ? (CustomObject)sessionAttributes.get("last") : null;
List<CustomObject> allObjects = MAPPER.convertValue(Constants.getAllObjects(), List.class);
int index = new Random().nextInt(tutti.size());
CustomObject new = allObjects.get(index);
// a simple method that contains allObjects.remove(index) because it didn't work here but also this cause an error
Constants.removeCustomObjectFromList(index);
sessionAttributes.put("ultimoNome", nuovoNome);
String title = Constants.SKILL_TITLE;
String primaryText =new.getTrue();
String secondaryText =(last!=null) ?last.getFalse() : "";
String speechText = "" + secondaryText + " "+primaryText + "?";
return input.getResponseBuilder()
.withSpeech(speechText)
.withSimpleCard(title, primaryText)
.withReprompt(speechText)
.build();
If I comment out the rows linked to the sessionAttribute and the Constants.removeCustomObjectFromList it works correctly but, as I said, the reference to sessionAttribute works correctly in another intent and I must remove CustomObjects from my initial list because the user should listen two time the same thing!
Could someone tell me where to find good info on this subject?
https://ask-sdk-for-nodejs.readthedocs.io/en/latest/Managing-Attributes.html
Above is the official docs. It can be a bit difficult to understand a couple things in there due to lack of extensive explanation, but for the most part everything you need is there. As for your issue, I don't know if this is the only cause, but I don't think getAttributesManager() is a function, unless that's something you've defined. Your code:
Map<String, Object> sessionAttributes = input.getAttributesManager().getSessionAttributes();
Can you try:
Map<String, Object> sessionAttributes = input.attributesManager.getSessionAttributes();
instead?
How can we select specific fields in Spring Data Mongo. I tried the following but I got cast exception from Foo to String.
Using #Query
#Query(value="{path : ?0}", fields="{path : 0}")
String findPathByPath(String path);
Non #Query
String findPathByPath(String path);
Here is the document model
#Document(collection = "foo")
public class Foo {
String name, path;
…
}
MongoDB only returns JSON documents for standard queries. What you'd like to see can be achieved by still returning a List<Foo>. The fields property in #Query will cause only the fields set to 1 being returned.
#Query(value="{ path : ?0}", fields="{ path : 0 }")
List<Foo> findByPath(String path);
We usually recommend introducing a dedicted DTO for that so that you prevent the partially filled Foo instance from being handed to save(…) in turn.
Another option is using the aggreation framework but that's more involved.
You can use
Query query = new Query();
query.fields().include("path");
You can use
public interface PersonRepository extends MongoRepository<Person, String>
#Query(value="{ 'firstname' : ?0 }",fields="{ 'firstname' : 1, 'lastname' : 1}")
List<Person> findByThePersonsFirstname(String firstname);
}
More information in spring data documentation
You can use below query to get specific fields.
#Query(fields="{path : 1}")
Foo findPathByPath(String path);
Records present in DB
{
"name" : "name2",
"path" : "path2"
},
{
"name" : "name3",
"path" : "path3"
}
Below query will return Foo object if path=Path3
{
"name": null,
"path": "path3"
}
we need to specify required fields with fieldName:1 and if don't require then specify it with 0.
I found this question while trying to get the value of a field from a specific object in my collection. From what my research shows, Mongo doesn't provide a way to natively return just a specific field's value from an object. (Disappointing since it seems pretty basic to be able to return just a specific value from a field like I would do in SQL or JSONPath).
To get around this, I wrote the following method using Spring MongoDB with Java 11:
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.MongoTemplate; //not used, just showing which type the template is
import java.util.Arrays;
import static java.util.Objects.requireNonNull;
/**
* Use this method to get a specific field from an object saved in Mongo. The objectId will be
* the id of the object to fetch, and the fieldValueToReturn will be the field to return.
*
* #return the value of the provided field-path converted to the class type provided
*/
public <T> T getFieldValueById(String objectId, String fieldValueToReturn, String collectionName, Class<T> classTypeToReturn) {
var query = new Query().addCriteria(Criteria.where("_id").is(objectId));
query.fields().include(fieldValueToReturn);
var result = mongoTemplate.findOne(query, org.bson.Document.class, collectionName);
requireNonNull(result, "Did not find any documents with id '" + objectId + "' in collection: " + collectionName);
return result.getEmbedded(Arrays.asList(fieldValueToReturn.split("\\.")), classTypeToReturn);
}
The getEmbedded call allows us to get the value of the nested field within the returned Bson document.
To use the method, just call it like this:
getFieldValueById("A1234", "field.nestedfield.nestedfield", "collectionName", String.class);
Hopefully this helps out someone else looking on how to do this.
As a side note, I'm not sure how to extend this to return a list of objects - if I get to that dilemma and solve it, I will try to update this answer. I'm also not sure if this is slower than running a Mongo aggregate query - I haven't tried running any performance comparisons between the two methods.
EDIT 2022-09-30: To return a list of a custom Pojo, it looks like you'll have to use an aggregate query via spring-data-mongodb. Also it seems basic queries are faster than aggregate queries, so use basic queries where possible.
You can directly pass your json query with #Query annotation, for example:
#Query("{ 'firstname' : 'john' }")
Here is the link to all json based queries in Spring Data MongoDb - https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.json-based
You can do the following.
In your repository, you have the method:
String findPathByPath(String path);
If the document looks like this (below), and you want to only return path
#Document(collection = "foo")
public class Foo {
String name;
String path;
String type;
…
}
Then create a Projection interface, e.g.
#Projection(name = "flattenedFoo", types = Foo.class)
public interface FlattenedInvoice {
String getPath(); // This returns the path value in Foo class
}
You can use the getter methods to get the fields from Foo that you are interested in.
Then in your get request, you would have to specify the projectionName.
e.g. with (#Resource path)
#RestResource(path = "findByPath", rel = "findByPath")
String findPathByPath(String path);
You could then say (In a get request):
..../findByPath?path=target_path&projection=flattenedFoo
this would then return a json with only the fields specifies in FlattenedFoo interface.
Is there a way to retrieve the value of a var in a .properties file and use is inside the same .properties file?
Insted of this (where I have to write manually the words 'Main Menu' in every line)
mainMenuTitle = Main Menu
NotBlank.menu.title = the field 'Main Menu' can't be null
Size.menu.title = the field 'Main Menu' must contains 10 characters
I want something like this (where I get automatically the value of the var 'mainMenuTitle')
mainMenuTitle = Main Menu
NotBlank.menu.title = the field **mainMenuTitle** can't be null
Size.menu.title = the field **mainMenuTitle** must contains 10 characters
You can get both message separately and then make a replace to inject the title
#Inject
public MessageSource messageSource;
public static String getMessage(String messageKey1, String messageKey12) {
String title = messageSource.getMessage(messageKey1, arguments, locale);
String message = messageSource.getMessage(messageKey2, arguments, locale).replace("**mainMenuTitle**", title);
}
This May be what you want, its a bit old , but may work for your needs.
Enabling constant substitution in Property Values
You can substitute a constant anywhere in the property value, and even have more than one constant within a value, as in the following example:
CONST_1 = shoes and ships
CONST_2 = sealing wax
SomeValue = {CONST_1} and {CONST_2}
In this example, the "SomeValue" property evaluates to "shoes and ships and sealing wax."
I have a Liferay scheduled job which should create new AssetCategories according to some rules. But I always get an AssetCategoryNameException. I have only letters, spaces and parenthesis in my new category's name/title, all of which I used in the existing category names. I also tried with constant string with english letters, with the same result. What could be the cause of this exception?
My code looks like this:
AssetCategoryLocalServiceUtil.addCategory(userId, 0, titleMap, null,
myVocabulary.getVocabularyId(), null, serviceContext);
userId is the id of a random Administrator user since it's a scheduled job and there is no "logged in" user.
titleMap is created with the following code: HashMap<Locale, String> titleMap = new HashMap<Locale, String>(); titleMap.put(myLocale, name);
serviceContext is a new ServiceContext object
And one more thing, how can I use the categoryProperties attribute of this method (after the problem is solved)? It is a String[], but properties are key-value pairs.
Following are invalid characters for AssetCategoryName
public static char[] INVALID_CHARACTERS = new char[] {
CharPool.AMPERSAND, CharPool.APOSTROPHE, CharPool.AT,
CharPool.BACK_SLASH, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
CharPool.COLON, CharPool.COMMA, CharPool.EQUAL, CharPool.GREATER_THAN,
CharPool.FORWARD_SLASH, CharPool.LESS_THAN, CharPool.NEW_LINE,
CharPool.OPEN_BRACKET, CharPool.OPEN_CURLY_BRACE, CharPool.PERCENT,
CharPool.PIPE, CharPool.PLUS, CharPool.POUND, CharPool.QUESTION,
CharPool.QUOTE, CharPool.RETURN, CharPool.SEMICOLON, CharPool.SLASH,
CharPool.STAR, CharPool.TILDE
};
Make sure your category name wont have any of these characters.
OK, I found the solution. The problem was caused by the locale settings. AssetCategory has both a name and a localized title, and the addAssetCategory method uses the title from the default locale as name. But in my case, the default locale was en_US while I was putting only hu_HU title in my titleMap. So, the title of the default locale was null, and that caused the exception (note: a NullPointerException would be more informative...). So I changed the default locale to my locale, and the code works.