aop.AopInvocationException: Null return value from - spring-mvc

here is the repository:
#Query(value = "select u.balance from User u where u.name=:name")
float toGetBalance(#Param("name") String name);
and here is the DAO interface:
boolean checkBalance(String userName, float totalPrice);
and here is the service
#Transactional(readOnly = true)
#Override
public boolean checkBalance(String userName, float totalPrice) {
if (userRepository.toGetBalance(userName) < totalPrice) {
return false;
} else {
return true;
}
}
and here is the error info:
org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract float com.repository.UserRepository.toGetBalance(java.lang.String)
and the type of balance is float!
what's wrong?

Change the signature of your repository to
#Query(value = "select u.balance from User u where u.name=:name")
Float toGetBalance(#Param("name") String name);
And it will simply return null if there is no such user in database with given name

#Query(value = "select u.balance from User u where u.name=:name")'
'Float toGetBalance(#Param("name") String name);
This exception arise because name not exist OR balance = NULL fpr the selected record in the table
So the query results no output. Spring JPA not able to bind the result with Return type Float.
Null return value from advice does not match primitive return type for: public abstract float com.repository.UserRepository.toGetBalance(java.lang.String)

Related

Realm java nested query on same ArrayObject

Current code:
mRealm.where(AdditionalData.class)
.contains("checklistParticipants.email", a#a.com, Case.INSENSITIVE)
.equalTo("checklistParticipants.type", 0)
.findAll();
which returns me result of similar to ANY record.
I want to check in nested query, only return record if and if both condition fulfilled. likewise in nested query, record email must be a#a.com and type=0
i tried below approach but ended up in same result.
mRealm.where(AdditionalData.class)
.contains("checklistParticipants.email",a#a.com, Case.INSENSITIVE)
.findAll()
.where()
.equalTo("checklistParticipants.type", 0)
.findAll();
Below screenshot shows 2 child items,
email= a#a.com & type = 1
email= x#x.com & type = 0
Realm checking for both value in either-or approach.
Also tried:
mRealm.where(AdditionalData.class)
.equalTo("checklistParticipants.email",a#a.com, Case.INSENSITIVE)
.and()
.equalTo("checklistParticipants.type", 0)
.findAll()
classpath "io.realm:realm-gradle-plugin:5.8.0"
UPDATE
class AdditionalData {
String name;
RealmList<ChecklistParticipants> checklistParticipants;
}
class ChecklistParticipants{
String email;
String type;
String field3;
}
as #EpicPandaForce said you need to use LinkingObjects
class AdditionalData {
String name;
#LinkingObjects(ChecklistParticipants.rlAdditionalData)
final RealmResults<ChecklistParticipants> linkedChecklistParticipants = null;
public RealmResults<RealmDocumentLines> getLinkedChecklistParticipants() {
return linkedChecklistParticipants ;
}
}
ChecklistParticipants
class ChecklistParticipants{
String email;
String type;
String field3;
AdditionalData rlAdditionalData;
public AdditionalData getAdditionalData() {
return rlAdditionalData;
}
public void setAdditionalData(AdditionalData additionalData) {
this.rlAdditionalData = additionalData ;
}
}
Then query
RealmResult<ChecklistParticipants> result = mRealm.where(ChecklistParticipants.class)
.contains("email", a#a.com, Case.INSENSITIVE)
.equalTo("type", 0)
.findAll();
then loop over the result and use getAdditionalData() from each item

Custom get and set on attribute

I am trying to setup a product key system in my application, but I want to ensure the attribute has the right size (16 characters).
I tried the following
public class ProductKey
{
public const int ProductKeyLength = 16;
[StringLength(ProductKeyLength, MinimumLength = ProductKeyLength)]
private string _value;
[Required]
[Index(IsUnique = true)]
public string Value {
get
{
var temp = Regex.Replace(this._value, ".{4}", "$0-");
return temp.Trim('-');
}
set { this._value = value.Replace("-", "");}
}
}
I want to enable the user to insert the key with our without hyphen. I get the following error with above code:
Column 'Value' in table 'dbo.ProductKeys' is of a type that is invalid for use as a key column in an index.
As I understood, I need to set a limit to Value so it can be used as a unique key. But, _value has a limit and _value is the actual representation of Value in the database.
Is there a way to set the limit correctly in this case?
Thanks in advance.
You are getting the error because without a StringLength attribute on the Value field, the database column gets created as VARCHAR(MAX) which cannot be used as a key. You need a [StringLength] on the field being used as a key. However, as your getter is returning the key formatted with dashes, you need the key length to be 19:
public class ProductKey
{
public const int ProductKeyLength = 19;
private string _value { get; set; }
[Key]
[Required]
[StringLength(ProductKeyLength, MinimumLength = ProductKeyLength)]
[Index(IsUnique = true)]
public string Value
{
get
{
var temp = Regex.Replace(this._value, ".{4}", "$0-");
return temp.Trim('-');
}
set { this._value = value.Replace("-", ""); }
}
}
You might be better off doing your format conversion in ViewModels and client-side code, as one problem you'll have here is searching - for example...
db.Keys.Add(new ProductKey { Value = "1234-5678-9012-3456" });
db.Keys.Add(new ProductKey { Value = "1234567890123455" });
db.SaveChanges();
Console.WriteLine(db.Keys.Count(k => k.Value.Contains("89"))); // 0
Console.WriteLine(db.Keys.Count(k => k.Value.Contains("8-9"))); // 2

Constraints on parameters in api interface

I've declared an API call in an interface and was wondering if it is possible to put constraints on some of the parameters. The API I'm accessing has these constraints as well and would like to enforce them in my program.
#GET("/recipes/search")
Call<RecipeResponse> getRecipes(
#Query("cuisine") String cuisine,
#Query("diet") String diet,
#Query("excludeIngredients") String excludeIngredients,
#Query("intolerances") String intolerances,
#Query("number") Integer number,
#Query("offset") Integer offset,
#Query("query") String query,
#Query("type") String type
);
How can I do this?
I know that it is possible to do this with POST request, and passing along an object via the RequestBody through the #Body annotation. Can I do this with a GET request too, where information is passed via the query string?
Thanks!
I think I ended up finding a solution. I've made a class SearchRecipeRequest in which I declare all possible parameters as class variables. In the setters I do the data validation such as checking for null on parameters that are required, or min/max value constraints on integers as specified by the endpoint. I then made a SearchRecipeRequestBuilder class to build such an object like so to make it easier to deal with all those possible parameters:
public class SearchRecipeRequestBuilder {
private String _cuisine = null,
_diet = null,
_excludeIngredients = null,
_intolerances = null,
_query = null,
_type = null;
private Integer _number = null,
_offset = null;
public SearchRecipeRequestBuilder() {}
public SearchRecipeRequest buildRequest() {
return new SearchRecipeRequest(_cuisine, _diet, _excludeIngredients, _intolerances, _number, _offset, _query, _type);
}
public SearchRecipeRequestBuilder cuisine(String cuisine) {
_cuisine = cuisine;
return this;
}
public SearchRecipeRequestBuilder diet(String diet) {
_diet = diet;
return this;
}
public SearchRecipeRequestBuilder excludeIngredients(String excludeIngredients) {
_excludeIngredients = excludeIngredients;
return this;
}
public SearchRecipeRequestBuilder intolerances(String intolerances) {
_intolerances = intolerances;
return this;
}
public SearchRecipeRequestBuilder query(String query) {
_query = query;
return this;
}
public SearchRecipeRequestBuilder type(String type) {
_type = type;
return this;
}
public SearchRecipeRequestBuilder number(Integer number) {
_number = number;
return this;
}
public SearchRecipeRequestBuilder offset(Integer offset) {
_offset = offset;
return this;
}
}
Which allows me to build the request like so:
SearchRecipeRequest request = new SearchRecipeRequestBuilder()
.query("burger")
.buildRequest();
I then pass along that object to a different function that knows how to use the request object to pass it along to the API.
That's how I'm doing it right now, if someone has a better way I'd love to hear it. :)
I got the idea to use the Builder pattern from a different StackOverflow question: Managing constructors with many parameters in Java.

Why is java.lang.Long not persistable?

I am trying to query for a list of ids of type Long in GAE/JDO. And I'm getting the following exception when I call detachCopyAll() on the result set.
org.datanucleus.jdo.exceptions.ClassNotPersistenceCapableException: The class "The class "java.lang.Long" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found." is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data for the class is not found.
at org.datanucleus.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:241)
at org.datanucleus.jdo.JDOPersistenceManager.jdoDetachCopy(JDOPersistenceManager.java:1110)
at org.datanucleus.jdo.JDOPersistenceManager.detachCopyAll(JDOPersistenceManager.java:1183)
...
I can query for a list of User objects and detach them just fine. I expected all primitive wrapper classes like Long to be persistable. What am I doing wrong? Below is the code I'm working with.
#PersistenceCapable(identityType=IdentityType.APPLICATION, detachable="true")
public class User
{
#PrimaryKey
#Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private Long id;
private String email;
}
#SuppressWarnings("unchecked")
public static List<Long> getUserKeys(String email)
{
assert email != null;
List<Long> keyList = null;
PersistenceManager pm = null;
Query query = null;
try {
pm = PMF.get().getPersistenceManager();
query = pm.newQuery("select id from " + User.class.getName());
query.declareParameters("String emailParam");
query.setFilter("email == emailParam");
List<Long> resultList = (List<Long>) query.execute(email);
// next line causes the ClassNotPersistenceCapableException
keyList = (List<Long>) pm.detachCopyAll(resultList);
}
finally {
if (query != null) query.closeAll();
if (pm != null) pm.close();
}
return keyList;
}
List<Long> resultList = (List<Long>) query.execute(email);
// next line causes the ClassNotPersistenceCapableException
keyList = (List<Long>) pm.detachCopyAll(resultList);
I don't understand what you are doing here. A List<Long> does not have to be detached. You'd want to detach instances of your User entity class, but a Long is a Long, and you can just do whatever you need to do with the resultList.
The error message is confusing, but just caused by Long not being an entity class.

C# check value exist in constant

I have declared my c# application constant this way:
public class Constant
public struct profession
{
public const string STUDENT = "Student";
public const string WORKING_PROFESSIONAL = "Working Professional";
public const string OTHERS = "Others";
}
public struct gender
{
public const string MALE = "M";
public const string FEMALE = "F";
}
}
My validation function:
public static bool isWithinAllowedSelection(string strValueToCheck, object constantClass)
{
//convert object to struct
//loop thru all const in struct
//if strValueToCheck matches any of the value in struct, return true
//end of loop
//return false
}
During runtime, I will like pass in the user inputted value and the struct to check if the value exist in the struct. The struct can be profession and gender. How can I achieve it?
Example:
if(!isWithinAllowedSelection(strInput,Constant.profession)){
response.write("invalid profession");
}
if(!isWithinAllowedSelection(strInput,Constant.gender)){
response.write("invalid gender");
}
You probably want to use enums, not structs with constants.
Enums gives you a lot of possibilities, it is not so hard to use its string values to save it to the database etc.
public enum Profession
{
Student,
WorkingProfessional,
Others
}
And now:
To check existence of value in Profession by value's name:
var result = Enum.IsDefined(typeof(Profession), "Retired"));
// result == false
To get value of an enum as a string:
var result = Enum.GetName(typeof(Profession), Profession.Student));
// result == "Student"
If you really can't avoid using value names with whitespaces or other special characters, you can use DescriptionAttribute:
public enum Profession
{
Student,
[Description("Working Professional")] WorkingProfessional,
[Description("All others...")] Others
}
And now, to get description from Profession value you can use this code (implemented here as an extension method):
public static string Description(this Enum e)
{
var members = e.GetType().GetMember(e.ToString());
if (members != null && members.Length != 0)
{
var attrs = members.First()
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length != 0)
return ((DescriptionAttribute) attrs.First()).Description;
}
return e.ToString();
}
This method fetches description defined in attribute and if there's none, returns value name. Usage:
var e = Profession.WorkingProfessional;
var result = e.Description();
// result == "Working Professional";

Resources