try
{
String jsonFilePath= "C:\\Users\\User-1\\Desktop\\ReqJSON\\student.json";
File jsonFile = new File(jsonFilePath);
mapper.writeValue(jsonFile, student);
}
catch (JsonGenerationException ex) {
ex.printStackTrace();
} catch (JsonMappingException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Showing posts with label Jackson Json Mapping. Show all posts
Showing posts with label Jackson Json Mapping. Show all posts
Wednesday, 18 September 2013
Java Object to JSON String Convertor
Thursday, 1 August 2013
Ignore a field coming from web service JSON response in Jackson Mapper
Use this annotation on the top of you response bean class
@JsonIgnoreProperties(ignoreUnknown=true)
Monday, 8 April 2013
Call Stored Procedures in Spring
There are multiple ways to call stored procedure in Spring Framework
Step 1: Create a store Procedure
In this example, we have extended abstract class StoredProcedure in our class called, EmployeeSP. This is declared as nested class inside EmployeeDAO because its only used by this class, if your stored procedure is used my multiple DAO classes, than you can also make it a top level class. If you look at constructor of EmployeeSP, it calls super class constructor and passes datasource and name of database stored procedure. We have also declared two stored procedure parameters, one is IN parameter id, and other is OUT parameter. Input to stored procedure is passed using IN parameter, and output from stored procedure is read using OUT parameter. Your stored procedure can have multiple IN and OUT parameter. StoredProcedure class also provide several execute() methods, which can be invoked to call stored procedure and get result. It return result as Map, where key is OUT parameter, and value is result of stored procedure.
1. query() method from JdbcTemplate to call stored procedures
2. extend abstract class StoredProcedure to call stored procedures
mysql> DELIMITER // mysql> create procedure usp_GetEmployeeName(IN id INT, OUT name VARCHAR(20)) -> begin -> select emp_name into name from employee where emp_id = id; -> end// Query OK, 0 rows affected (0.52 sec) mysql> DELIMITER ;Step2: Java Class which wraps Stored procedure
In this example, we have extended abstract class StoredProcedure in our class called, EmployeeSP. This is declared as nested class inside EmployeeDAO because its only used by this class, if your stored procedure is used my multiple DAO classes, than you can also make it a top level class. If you look at constructor of EmployeeSP, it calls super class constructor and passes datasource and name of database stored procedure. We have also declared two stored procedure parameters, one is IN parameter id, and other is OUT parameter. Input to stored procedure is passed using IN parameter, and output from stored procedure is read using OUT parameter. Your stored procedure can have multiple IN and OUT parameter. StoredProcedure class also provide several execute() methods, which can be invoked to call stored procedure and get result. It return result as Map, where key is OUT parameter, and value is result of stored procedure.
import java.sql.Types;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class EmployeeDao
{
private JdbcTemplate jdbcTemplate;
private EmployeeSP sproc;
public void setDataSource(DataSource source)
{
this.jdbcTemplate = new JdbcTemplate(source);
this.sproc = new EmployeeSP(jdbcTemplate.getDataSource());
}
/* * wraps stored procedure call */
public String getEmployeeName(int emp_id)
{
return (String) sproc.execute(emp_id);
}
/* * Inner class to implement stored procedure in spring. */
private class EmployeeSP extends StoredProcedure
{
private static final String SPROC_NAME = "usp_GetEmployeeName";
public EmployeeSP( DataSource datasource )
{
super( datasource, SPROC_NAME );
declareParameter( new SqlParameter( "id", Types.INTEGER) ); //declaring sql in parameter to pass input
declareParameter( new SqlOutParameter( "name", Types.VARCHAR ) ); //declaring sql out parameter
compile();
}
public Object execute(int emp_id)
{
Map results = super.execute(emp_id);
return results.get("name"); //reading output of stored procedure using out parameters
}
}
}
}
}
}
Step3: Test stored procedure
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/* * Main class to start and test this Java application */
public class Main
{
public static void main(String args[])
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
EmployeeDao dao = (EmployeeDao) ctx.getBean("employeeDao"); //calling stored procedure using DAO method
System.out.println("Employee name for id 103 is : " + dao.getEmployeeName(103)); } }
}
}
Output:
2013-01-17 23:56:34,408 0 [main] DEBUG EmployeeDao$EmployeeSP - Compiled stored procedure. Call string is [{call usp_GetEmployeeName(?, ?)}]
2013-01-17 23:56:34,439 31 [main] DEBUG EmployeeDao$EmployeeSP - RdbmsOperation with SQL [usp_GetEmployeeName] compiled
Employee name for id 103 is : Jack
spring-config.xml
classpath:jdbc.properties
Monday, 1 April 2013
Spring MVC’s @ModelAttribute Annotation
The @ModelAttribute annotation is used as part of a Spring MVC web app and can be used in two scenarios.
To demonstrate the @ModelAttributes, I'm using the simplest of scenarios: adding a user account to a hypothetical system and then, once the user account has been created, displaying the new user’s details on a welcome screen.
In order to start the ball rolling, I’ll need a simple User bean with some familiar fields: first name, last name, nick name and email address - the usual suspects.
I’ll also need a Spring MVC controller to handle creating users. This will contains a couple of important methods that use the @ModelAttribute annotation, demonstrating the functionality outlined above.
The method below demonstrates how to bind a method return value to a model.
Just for the record, this is the full controller code.
- Firstly, it can be used to inject data objects the model before a JSP loads. This makes it particularly useful in ensuring that a JSP has all the data is needs to display itself. The injection is achieved by binding a method return value to the model.
- Secondly, it can be used to read data from an existing model assigning it to handler method parameters.
To demonstrate the @ModelAttributes, I'm using the simplest of scenarios: adding a user account to a hypothetical system and then, once the user account has been created, displaying the new user’s details on a welcome screen.
In order to start the ball rolling, I’ll need a simple User bean with some familiar fields: first name, last name, nick name and email address - the usual suspects.
public class User {
private String firstName;
private String lastName;
private String nickName;
private String emailAddress;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
I’ll also need a Spring MVC controller to handle creating users. This will contains a couple of important methods that use the @ModelAttribute annotation, demonstrating the functionality outlined above.
The method below demonstrates how to bind a method return value to a model.
/**
* This creates a new User object for the empty form and stuffs it into
* the model
*/
@ModelAttribute("User")
public User populateUser() {
User user = new User();
user.setFirstName("your first name");
user.setLastName("your last name");
return user;
}
This method is called before every @RequestMapping annotated handler method to add an initial object to the model, which is then pushed through to the JSP. Notice the word every in the above sentence. The @ModelAttribute annotated methods (and you can have more than one per controller) get called irrespective of whether or not the handler method or JSP uses the data. In this example, the second request handler method call doesn’t need the new user in the model and so the call is superfluous. Bare in mind that this could possibly degrade application performance by making unnecessary database calls etc. It’s therefore advisable to use this technique only when each handler call in your Controller class needs the same common information adding to the model for every page request. In this example, it would be more efficient to write:
/**
* Create the initial blank form
*/
@RequestMapping(value = PATH, method = RequestMethod.GET)
public String createForm() {
populateUser();
return FORM_VIEW;
}
The method below demonstrates how to annotate a request method argument, so that data is extracted from the model and bound to the argument.
/**
* This is the handler method. Stick the user bean into a new attribute for
* display on the next page
*
* @param user
* The user bean taken straight from the model
* @param model
* An out param. Takes the user and adds it to the model FOR the
* NEXT page under a different name.
*
*/
@RequestMapping(value = PATH, method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user,
BindingResult result, Model model) {
model.addAttribute("newUser", user);
return WELCOME_VIEW;
}
In this example, an ‘add user’ button on a form has been pressed calling the addUser() method. The addUser() method needs a User object from the incoming model, so that the new user’s details can be added to the database. The @ModelAttribute("user") annotation applied takes any matching object from the model with the “user” annotation and plugs it into the User user method argument.Just for the record, this is the full controller code.
@Controller
public class AddUserController {
private static final String FORM_VIEW = "adduser.page";
private static final String WELCOME_VIEW = "newuser.page";
private static final String PATH = "/adduser";
/**
* Create the initial blank form
*/
@RequestMapping(value = PATH, method = RequestMethod.GET)
public String createForm() {
return FORM_VIEW;
}
/**
* This creates a new User object for the empty form and stuffs it into
* the model
*/
@ModelAttribute("User")
public User populateUser() {
User user = new User();
user.setFirstName("your first name");
user.setLastName("your last name");
return user;
}
/**
* This is the handler method. Stick the user bean into a new attribute for
* display on the next page
*
* @param user
* The user bean taken straight from the model
* @param model
* An out param. Takes the user and adds it to the model FOR the
* NEXT page under a different name.
*
*/
@RequestMapping(value = PATH, method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user,
BindingResult result, Model model) {
model.addAttribute("newUser", user);
return WELCOME_VIEW;
}
}
Thursday, 14 March 2013
Spring Core
Spring Core Tutorials
Spring Bean Scope
Spring 3 - Task Scheduling
Call Stored Procedures in Spring
Measuring elapsed time using Spring StopWatch
Basic Spring Example With ClassPathXmlApplicationContext & AnnotationConfigApplicationContext
Schedule tasks in Spring 3 Using @Scheduled
Autowire a Bean Spring
Auto-Wiring Beans Spring
@InitBinder - Custom Spring Validator to a Spring MVC Controller
About Spring Framework
Spring Bean Scope
Spring 3 - Task Scheduling
Call Stored Procedures in Spring
Measuring elapsed time using Spring StopWatch
Basic Spring Example With ClassPathXmlApplicationContext & AnnotationConfigApplicationContext
Schedule tasks in Spring 3 Using @Scheduled
Autowire a Bean Spring
Auto-Wiring Beans Spring
@InitBinder - Custom Spring Validator to a Spring MVC Controller
About Spring Framework
Subscribe to:
Posts (Atom)