Home > Net >  How to create a field of data type varchar in controller class
How to create a field of data type varchar in controller class

Time:10-15

enter image description here How do I create a field of data type varchar in my controller class with size as 20? Also, could anyone please tell me how to create a field of data type none. Also, how to mention the fields to be mandatory?

I am quite beginner in this. Any help would be appreciated.

CodePudding user response:

you cannot declare varchar in controller you have to use String private String str = ""; or you can use this

StringBuilder str 
            = new StringBuilder();
str.setLength(20);  

CodePudding user response:

Ok, so your question is lacking context so I am going to make some assumptions. I'm assuming that you have to implement some controller that exposes an URL endpoint. I assume that you want to be able to receive data on that endpoint and map it to an object (dto). I assume that you want to assure that you want to perform validitions on the received data.

Im on my phone so I won't write it out completely but let me give you some pointers.

Create a dto object with the data structure that you're expecting to receive. Create a contreoller with @Controller annotation. Within the controller, create a method with the @postMapping annotation and configure it appropriately. The method should accept the dto class and a binding result class as method parameter. Within the method definition use the @Valid annotation before the dto class. The informs Spring to validate the dto and it will inject the valdition result into the Binding Result object. Note that the latter should be mentioned after the dto, in this example it would be the second and last parameter.

Now in the dto, you can annotate the class fields with annotations from the javax.validation package. For example @NotNull or @Size which could assert the size of a string field and assure the availability of a field value. Note that I believe in later versions of Java, the validation package was moved to Jakarta package so take that into consideration. Also make sure to use the right annotations, for example there is also @Nonnull from spring which does other stuff.

Now, within the method body you can now assert if there where any binding result errors. Just check the BindingResult.hasErrors() and then handle them appropriately.

The field of data type None does not ammake sense to me so will need more information to be able to help with that.

  • Related