i am new in web services, am using spring-boot for creating web services, whereas, while giving the request with http://localhost:8085/user/30?name=abc, I am getting null for the id property.`
#GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(#PathParam("id") Long id,
#QueryParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}
edited to add screenshot.
screenshot taken from Postman
Thanks in advance.
You need to use #PathVariable because you are using spring-rest not #PathParam that is a JAX-RS annotation
#GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(#PathVariable("id") Long id,
#QueryParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}
I noticed you are mixing Jax-RS annotation with Spring annotation
Try this and it will fix your problem
#GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(#PathVariable("id") Long id,
#RequestParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}
For the id variable you must use #PathVariable annotation and for the name parameter use #RequestParam.
Here is a full working solution:
#RestController
#RequestMapping("/user")
public class UserController {
#GetMapping("/{id}")
public String getUser(#PathVariable Long id, #RequestParam String name) {
System.out.println(" Got id by path param : " + id + " And Got name using Query Param " + name);
return " Got id by path param : " + id + " And Got name using Query Param " + name;
}
}
See here for more details.
Now when you make a request
$ curl http://localhost:8085/user/30?name=abc
you get a response:
Got id by path param : 30 And Got name using Query Param abc
Related
I have a problem to write the syntax using an enum in a if in MyBatis annotation.
#Delete("<script>DELETE FROM tb_a WHERE "
+ "<if test='context.name().equals(ALBUM)'>"
+ " album_id = #{id}"
+ "</if>"
+ "<if test='context.name().equals(VIDEOLIBRARY)'>"
+ " videolibrary_id = #{id}"
+ "</if>"
+ "</script>")
boolean delete(#Param("id") int id, #Param("context") EContext context);
Enum
public enum EContext {
ALBUM,
VIDEOLIBRARY,
IMAGE,
VIDEO,
}
the correct syntax as fare I know is like this <if test="context.name().equals('ALBUM')">
But I don't know how to write it with annotation.
I get this error message
Thanks for your help
Edited to show more about the code
name() method returns a java.lang.String and in OGNL, a string literal should be enclosed in single or double quotes.
So, the if element should be written as..
+ "<if test=\"context.name().equals('ALBUM')\">"
or
+ "<if test='context.name().equals(\"ALBUM\")'>"
I am using MyBatis (mybatis-spring-boot-starter 2.0), I want to insert list of values into table using java sqlBuilder. I know how to write sqlBuilder in java for storing single record. But how to write the sqlBuilder for List of records?
Mapper interface (Single record):
#InsertProvider(method = "insert", type = TestSqlBuilder.class)
#Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
public void save(final TestVO testVO );
TestSqlBuilder.java (Single record):
The below method used for inserting single TestVO values.
public String insert() {
return new SQL() {
{
INSERT_INTO("TEST")
.VALUES("COL1", "#{col1}")
.VALUES("COL2", "#{col2}")
.VALUES("COL3", "#{col3}")
.VALUES("COL3", "#{col4}")
.toString();
}
}.toString();
}
Now for List of records, how to write sqlBuilder.
Else how can we convert the below to sqlBuilder java code
#Insert("<script> "
+ "insert into sys_user "
+ "(t_id, t_name, t_age) "
+ "values "
+ "<foreach collection='list' item='item' "
+ " index='index' separator=','> "
+ "(#{item.id}, #{item.name}, #{item.age}) "
+ "</foreach> "
+ "</script> ")
int insertUserListWithForeach(List<User> list);
I'm Using the CRM SDK from PowerShell, Trying to query a contract linked to specific Account name, If I do the query against Account GUID I get the results, but I want to query against the name inside the EntityReference object, and not the GUID, for example (this works fine):
$query = new-object Microsoft.Xrm.Sdk.Query.QueryExpression('new_contract')
$query.Criteria.AddCondition('new_account', [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Equal, $AccountGuid)
The Above results looks like that:
Key Value
--- -----
createdby Microsoft.Xrm.Sdk.EntityReference
createdon 21/10/2014
modifiedby Microsoft.Xrm.Sdk.EntityReference
modifiedon 28/02/2016
modifiedonbehalfby Microsoft.Xrm.Sdk.EntityReference
new_account Microsoft.Xrm.Sdk.EntityReference
[...] [...]
The new_account Properties are:
Id : dab2909d-6149-e411-93fc-005056af5481
LogicalName : account
Name : CustomerNameText
KeyAttributes : {}
RowVersion :
ExtensionData : System.Runtime.Serialization.ExtensionDataObject
I want to create a Query for new_contract with new_account Name LIKE CustomerNameText
I tried:
$query.Criteria.AddCondition('new_account',([Microsoft.Xrm.Sdk.EntityReference].Attributes['new_account']).Name, [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Like, $AccountName)
But it not works get the following error:
Exception calling "RetrieveMultiple" with "1" argument(s): "Link entity with name or alias new_account is not found"
At line:2 char:5
+ $temp = $service.RetrieveMultiple($query);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FaultException`1
I hope i'm clear, but if not, comment with any question.
Powershell code is preferable, c# is ok as well
Thanks...
You cannot use QueryExpression criteria for EntityReference name. With EntityReference you can only use Guid.
If you want to Query by name, you can use LinkEntity in QueryExpression. You will have to use LinkCriteria
var q = new QueryExpression();
q.EntityName = "new_contract";
q.ColumnSet = new ColumnSet();
q.ColumnSet.Columns.Add("new_contractid");
q.LinkEntities.Add(new LinkEntity("new_contract", "account", "new_account", "accountid", JoinOperator.Inner));
q.LinkEntities[0].Columns.AddColumns("accountid", "name");
q.LinkEntities[0].EntityAlias = "temp";
q.LinkEntities[0].LinkCriteria.AddCondition("name", ConditionOperator.Equal, "yourAccountName");
P.SIf the above snippet, is not working for you. And you want to retrieve by accountName. On way to do this is use your existing code using Guid of account. But first you have to retrieve accountGuid by name. In that case
public Guid getAccountGuidByName(string name)
{
QueryExpression accountQuery = new QueryExpression("account");
accountQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "yourAccountName");
EntityCollection entCol = Service.RetrieveMultiple(accountQuery);
if (entCol.Entities.Count > 0)
{
return entCol.Entities[0].Id;
}
return Guid.Empty;
}
just for example i don't know how can you call function etc in powershell but i am providing c# code, as you said its ok if it in C# then use it like below :
$query = new-object Microsoft.Xrm.Sdk.Query.QueryExpression('new_contract')
$query.Criteria.AddCondition('new_account', [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Equal, getAccountGuidByName("yourAccountName"));
I am using table-valued functions with Entity Framework 5. I just received this error:
A parameter named 'EffectiveDate' already exists in the parameter collection. Parameter names must be unique in the parameter collection. Parameter name: parameter
It is being caused by me joining the calls to table-valued functions taking the same parameter.
Is this a bug/limitation with EF? Is there a workaround? Right now I am auto-generating the code (.edmx file).
It would be really nice if Microsoft would make parameter names unique, at least on a per-context basis.
I've created an issue for this here.
In the meantime, I was able to get this to work by tweaking a few functions in the .Context.tt file, so that it adds a GUID to each parameter name at runtime:
private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) {
if (typeMapper.IsComposable(edmFunction))
{
#>
[EdmFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")]
<#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#>
{ var guid = Guid.NewGuid().ToString("N"); <#+
codeStringGenerator.WriteFunctionParameters(edmFunction, " + guid", WriteFunctionParameter);
#>
<#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#>
} <#+
}
else
{
#>
<#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#>
{ <#+
codeStringGenerator.WriteFunctionParameters(edmFunction, "", WriteFunctionParameter);
#>
<#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#>
} <#+
if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption))
{
WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true);
}
} }
...
public void WriteFunctionParameters(EdmFunction edmFunction, string nameSuffix, Action<string, string, string, string> writeParameter)
{
var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
{
var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\"" + nameSuffix + ", " + parameter.FunctionParameterName + ")";
var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\"" + nameSuffix + ", typeof(" + parameter.RawClrTypeName + "))";
writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
}
}
...
public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
{
var parameters = _typeMapper.GetParameters(edmFunction);
return string.Format(
CultureInfo.InvariantCulture,
"return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
_typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
edmFunction.NamespaceName,
edmFunction.Name,
string.Join(", ", parameters.Select(p => "#" + p.EsqlParameterName + "\" + guid + \"").ToArray()),
_code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
}
Not a bug. Maybe a limitation or an omission. Apparently this use case has never been taken into account. EF could use auto-created parameter names, but, yeah, it just doesn't.
You'll have to resort to calling one of the functions with .AsEnumerable(). For some reason, this must be the first function in the join (as I have experienced). If you call the second function with .AsEnumerable() it is still translated to SQL and the name collision still occurs.
I am having a problem with the Dynamic Linq Library. I get a the following error "ParserException was unhandled by user code ')" or ','". I have a Dicitionary and I want to create a query based on this dictionary. So I loop through my dictionary and append to a string builder "PersonId = (GUID FROM DICTIONARY). I think the problem is were I append to PersonId for some reason I can't seem to convert my string guid to a Guid so the dynamic library don't crash.
I have tried this to convert my string guid to a guid, but no luck.
query.Append("(PersonId = Guid(" + person.Key + ")");
query.Append("(PersonId = " + person.Key + ")");
I am using VS 2010 RTM and RIA Services as well as the Entity Framework 4.
//This is the loop I use
foreach (KeyValuePair<Guid, PersonDetails> person in personsDetails)
{
if ((person.Value as PersonDetails).IsExchangeChecked)
{
query.Append("(PersonId = Guid.Parse(" + person.Key + ")");
}
}
//Domain service call
var query = this.ObjectContext.Persons.Where(DynamicExpression.ParseLambda<Person, bool>(persons));
Please help, and if you know of a better way of doing this I am open to suggestions.
For GUID comparison with dynamic linq use query properties and the Equals() method like in the provided sample.
var items = new[]
{
new { Id = Guid.Empty },
new { Id = Guid.NewGuid() },
new { Id = Guid.NewGuid() },
new { Id = Guid.NewGuid() }
};
var result = items.AsQueryable()
.Where("Id.Equals(#0)", Guid.Empty)
.Any();
Use a parameterized query, e.g.:
var query = this.ObjectContext.Persons.Where(
"PersonId = #1", new [] { person.Key } );
Did you try(notice the extra ')' ).
query.Append("(PersonId = Guid(" + person.Key + "))");