spring MVC LazyInitialisationException - spring-mvc

we are working on springMVC java config app. I am facing a problem every time when i trying to view child object properties but getting lazyinitialisationexception no session error. this i am getting on ajax calls also. I know that eager fetching is one solution and Hibernate.initailize(child) is another. But what is the standard way to resolve this?
My entities are like this
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "COUNTRY_DETAILS")
public class Country implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Set<State> states;
#Id
#GeneratedValue
#Column(name = "ID", length = 20, nullable = false)
public Long getId() {
return id;
}
public void set Id(Long id) {
this.id = id;
}
#Column(name = "NAME", length = 20, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Country() {
super();
// TODO Auto-generated constructor stub
}
public Country(String name) {
super();
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "countryId")
public Set<State> getStates() {
return states;
}
public void setUnits(Set<State> states) {
this.states = states;
}
}
States entity
#Entity
#Table(name = "State_DETAILS")
public class State implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "State_ID", length = 20, nullable = false)
private Long StateId;
#Column(name = "State_NAME", length = 20, nullable = false)
private String StateName;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Country_ID", nullable = false, //
foreignKey = #ForeignKey(name = "Country_DETAIL_State_FK") )
private Country countryId;
Public Long getStateId() {
return StateId;
}
public void setStateId(Long StateId) {
this.StateId = StateId;
}
public String getStateName() {
return StateName;
}
public void setStateName(String StateName) {
this.StateName = StateName;
}
public Country getCountryId() {
return countryId;
}
public void setCmdId(Country countryId) {
this.countryId = countryId;
}
public State(Long StateId) {
super();
this.StateId = StateId;
}
public State() {
super();
// TODO Auto-generated constructor stub
}
}
My Controller
This is my controler
#RequestMapping(value = "/findStatesByCountry", method = RequestMethod.GET)
public #ResponseBody List<State> findAllStateByCountryId() {
Country c=new Country();
c.setId((long) 1);
List<State> states=stateService.getStatesByCommand(c);
return units;
}
Error I am getting is
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: could not initialize proxy - no Session
I want to show in view like country.state.stateId ,state.country.name e.t.c .
How to resolve this type of situation?
Eager is the not the solution i want to use

Found the answer finally.OpenEMInViewFilter is the solution..I tried the following and working fine...
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I have used interceptor also..
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping
path="/resources/**"/>
<bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor"
/>
</mvc:interceptor>
</mvc:interceptors>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
it is working fine now and able to fetch associations in views.Let me know if any cons in this type of usage...
Thanx

Related

Spring JPA: Adding an entity with current user ID as foreign key

I'm using a Thymeleaf HTML registration form and simple save/update method to save/update a 'dish' object to a mySQL database. Restaurant Id is a foreign key for the 'dish' but using the below methods it saves as 'null',
I would like to make it so that the Restaurant id of the currently logged in restaurant owner saves automatically when they add a dish.
Is there an uncomplicated way to do this? The closest tutorial I've found on Youtube involves using JSON requests in Postman and I've had issue adapting that to a HTML registration form in the past.
I'm quite new to all of this so any help would be very much appreciated!
See Dish class:
package com.bron.demoJPA.appuser;
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#ToString(exclude = "reqlist")
public class Dish {
#Id
#SequenceGenerator(name = "dish_sequence", sequenceName = "dish_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dish_sequence")
#Column(name = "dish_Id")
private Long dishId;
#Column(name = "dish_name")
private String dname;
#Column(name = "dish_description")
private String description;
#Column(name = "dish_price")
private double price;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "Rest_ID", referencedColumnName = "Rest_ID")
private AppUser app;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "dish_requirment_mapping", joinColumns = #JoinColumn(name = "dish_Id", referencedColumnName = "dish_Id"), inverseJoinColumns = #JoinColumn(name = "Require_ID", referencedColumnName = "Require_ID"))
private List<Requirments> reqlist;
public void addRequirments(Requirments req) {
if (reqlist == null)
reqlist = new ArrayList<>();
reqlist.add(req);
}
}
See AppUser(restaurant owner) Class
#Column(name = "Rest_Password")
private String password;
#Column(name = "Rest_Email_Address")
private String email;
#Enumerated(EnumType.STRING)
private AppUserRole appUserRole;
private Boolean locked = false;
// don't enable user until email verification
private Boolean enabled = false;
public AppUser(String restname, String email, String pass, AppUserRole app) {
this.restaurantName = restname;
this.email = email;
this.password = pass;
this.appUserRole = app;
}
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(appUserRole.name());
return Collections.singletonList(authority);
}
#Override
public String getUsername() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true)
#JoinColumn(name = "openingHourID", referencedColumnName = "OpeningHour_ID")
private OpeningHour opening;
}
See Controller class:
package com.bron.demoJPA.conroller;
#Controller
public class DishController {
//display list of employees
#Autowired
private DishService dishService;
#GetMapping("/dish")
public String viewHomePage(Model model) {
model.addAttribute("listDish", dishService.getAllDish());
return "index";
}
#GetMapping("/showNewDishForm")
public String showNewDishForm(Model model) {
// Create model attribute to bind form data
Dish dish = new Dish();
model.addAttribute("dish", dish);
return "new_dish";
}
#PostMapping("/saveDish")
public String saveDish(#ModelAttribute("dish") Dish dish) {
// save dish to database
dishService.saveDish(dish);
return "redirect:/dish";
}
#GetMapping("/showFormForUpdate/{dishId}")
public String showFormForUpdate(#PathVariable(value = "dishId") long dishId, Model model) {
// get dish from service
Dish dish = dishService.getDishByDishId(dishId);
// set dish as model to pre-populate the form data
model.addAttribute("dish", dish);
return "update_dish";
}
}
See Service implementation
package com.bron.demoJPA.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bron.demoJPA.appuser.Dish;
import com.bron.demoJPA.repository.DishRepository;
#Service
public class DishServiceImpl implements DishService {
#Autowired
private DishRepository dishRepository;
#Override
public List<Dish> getAllDish() {
return dishRepository.findAll();
}
#Override
public void saveDish(Dish dish) {
this.dishRepository.save(dish);
}
#Override
public Dish getDishByDishId(long dishId) {
Optional<Dish> optional = dishRepository.findById(dishId);
Dish dish = null;
if (optional.isPresent()) {
dish = optional.get();
} else {
throw new RuntimeException("Dish not found for: " + dishId);
}
return dish;
}
}
See Service class
public interface DishService {
List<Dish> getAllDish();
void saveDish(Dish dish);
Dish getDishByDishId(long dishId);
}
Can you make sure Dish's "app" attribute is being set correctly before trying to save it?
If it's null or it's a brand new instance of AppUser class it makes sense that when trying to match and persist it ends up on null.
Greetings!

Unable to get insert, update and delete to work with spring-data-jpa

I am trying to create a web service that performs basic CRUD operations written using spring boot 2. The select operation works fine, however the insert, delete and update operations have no effect as their query is not getting generated and executed.
I have looked through different examples but I am unable to figure out any issues. The major concern for me is the fact that not even a query is being triggered for insert, delete or update operations.
Student Entity
#Entity
#Table(name = "student")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Student {
#Id
#NotNull
#Column(name = "id")
private int id;
#NotNull
#Column(name = "name")
private String name;
#Column(name = "course")
private String course;
public Student(int id, String name, String course) {
this.id = id;
this.name = name;
this.course = course;
}
public Student(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
#Override
public String toString() {
return "Student{ id=" + id + ", name='" + name + '\'' + ", course='" + course + '\'' + '}';
}
}
StudentDaoImpl
#Repository
#Transactional
public class StudentDaoImpl implements StudentDao {
#Autowired
private EntityManagerFactory entityManagerFactory;
#Override
public List<Student> fetchAllStudents() {
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
Root<Student> root = cq.from(Student.class);
CriteriaQuery<Student> all = cq.select(root);
List<Student> solution = session.createQuery(all).getResultList();
session.close();
return solution;
}
#Override
public Student deleteStudent(Integer id) {
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
Student student = session.load(Student.class, id);
if (student != null){
session.delete(student);
session.close();
}
return student;
}
#Override
public Student fetchForId(Integer id){
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
Student student = session.load(Student.class, id);
session.close();
return student;
}
#Override
public Student insertStudent(Student student) {
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
session.save(student);
session.close();
return student;
}
#Override
public Student updateStudent(Student student) {
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
Student studentCheck = session.load(Student.class, student.getId());
if (studentCheck != null) {
session.saveOrUpdate(student);
session.close();
}
return student;
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Edit
Replacing EntityManagerFactory with EntityManager( + Persistent Context Annotation) worked for me. However I still haven't figured why persistence worked for EntityManager.
If it's not strictly important, you can do it using NativeQuery and its executeUpdate API:
String query = "insert into student values(1,?)";
em.createNativeQuery(query)
.setParameter(1, "Tom")
.executeUpdate();
I would like to suggest this repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
}
Probably you have to change the id of Student from int to Integer.
And this repository has the methods for retrieving, updating, creating and deleting.
Let's say that you want to use this repository in a Service, you can do that like this:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional(rollbackFor = Exception.class)
public class StudentService {
#Autowired
private StudentRepository studentRepository;
......
}

I am new In spring & Hibernate How To add profile image path in database using Springs 3 MVC

Value Object Class
package com.admin.modelVO;
import java.sql.Timestamp;
public class UserProfileVO{
private String userName;
private String password;
private String fName;
private String lName;
private String dob;
private String emailId;
private String contactNo;
private String gender;
private String photo;
private Timestamp createdDate;
private Boolean status;
private Integer rollId;
public Integer getRollId() {
return rollId;
}
public void setRollId(Integer rollId) {
this.rollId = rollId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
}
Second Controller
package com.admin.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.admin.modelVO.UserProfileVO;
import com.admin.service.UserProfileService;
#Controller
public class UserProfileController{
#Autowired
UserProfileService userProfileService;
#RequestMapping(value="/userprofile1",method = RequestMethod.GET)
public String userprofile1(#ModelAttribute("UserProfileVO") UserProfileVO userProfileVO,ModelMap modelMap, HttpServletRequest request, HttpServletResponse response){
return "userprofile1";
}
#RequestMapping(value="/userprofile",method = RequestMethod.POST)
public String userprofile(#ModelAttribute("UserProfileVO") UserProfileVO userProfileVO,ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirect){
String result=userProfileService.listUserProfile(userProfileVO);
request.setAttribute("userlist", result);
System.out.println("dfghdfg"+result);
return "success";
}
}
3.DaoImplement
package com.admin.daoImpl;
import java.sql.Timestamp;
import java.util.Date;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.admin.dao.UserProfileDao;
import com.admin.entity.Usermaster;
import com.admin.modelVO.UserProfileVO;
#Repository
public class UserProfileDaoImpl implements UserProfileDao{
#Autowired
SessionFactory sessionFactory;
Date date=new Date();
public String listUserProfile(UserProfileVO userProfileVO) {
String userId=null;
Usermaster userMaster=new Usermaster();
sessionFactory.getCurrentSession().beginTransaction();
userMaster.setUsername(userProfileVO.getUserName());
userMaster.setPassword(userProfileVO.getPassword());
userMaster.setFname(userProfileVO.getfName());
userMaster.setLname(userProfileVO.getfName());
userMaster.setDob(userProfileVO.getDob());
userMaster.setEmail(userProfileVO.getEmailId());
userMaster.setGender(userProfileVO.getGender());
userMaster.setContactNo(userProfileVO.getContactNo());
userMaster.setPhoto(userProfileVO.getPhoto());
userMaster.setStatus(true);
userMaster.setCreatedDate(date);
userMaster.setRoleId(2);
sessionFactory.getCurrentSession().save(userMaster);
System.out.println("dsfsf"+userMaster);
sessionFactory.getCurrentSession().getTransaction().commit();
return userId;
}
}
I want to upload profile picture with registration page and i want to set contxt path on database and image is perticulor folder. i will post you DaoImpl VO and Controller where we put the code and my object is "PHOTO" so i want to stored it
You can refer following method to handle image uploading i.e. multipart request. You can not this method directly in your code. This is for understanding only.
For this you will need :
commons-fileupload.jar
and
commons-io.jar
public String handleFileUpload(HttpServletRequest request,
#RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
System.out.println("description: " + request.getParameter("description"));
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
if (!aFile.getOriginalFilename().equals("")) {
aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
}
}
}
// returns to the view "Result"
return "Result";
}
Here: "saveDirectory" string variable can be any path on your server, where you want to store files.
in configuration you will need to add:
#Bean(name = "multipartResolver")
public CommonsMultipartResolver getMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxInMemorySize(1048576);
multipartResolver.setMaxUploadSize(20971520);
return multipartResolver;
}
EDIT :
// get absolute path of the application
ServletContext context = request.getServletContext();
String saveDirectory = context.getRealPath("");
System.out.println("saveDirectory = " + saveDirectory);
You dont have to store whole path to the file. Just store file name (that you can give any unique name every time). So in DAOImpl write code for storing filename.

SpringMVC #JsonDeserialize doesn't work

I got a very simple POJO like below:
#Entity
#Table(name = "people")
public class People(){
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer peopleId;
private Date birthday;
#JsonDeserialize(using = DateDeserializer.class)
public void setBirthday(Date birthday){
this.birthday = birthday;
}
}
DateDeserializer:
public class DateDeserializer extends JsonDeserializer<Date> {
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
System.out.print("abc2222222222222222222222222222");
return new Date();
}
}
However this deserializer never be invoked at all, I tested #JSonSerializer which works perfectly. is there anything I did wrongly or missed something?

Spring MVC and java script(addRows function) binding

I have question/issue with javascript function binding in Spring MVC . As per our requirement I need to insert a NEW ROW in a table when the user clicks on “ADD” button .
Step1 : So when the user clicks on “Add MORE” button I inserting a new row within a table , I am handling this using javascript
Step 2: When user clicks on the submit button , I Need to send the values entered by user to my Controller (Spring MVC Controller) .
So how can binding the values to controller dynamically ?
Please help me to resolve this issue ASAP .
I do the following when I need to bind a dynamic list of objects coming from the front end :
Post the data as a json array, i.e. in the following format
{ data : [{a:1, b:2}, {a:3, b:4}] }
In the Controller
#RequestMapping(value="save", method=RequestMethod.POST)
public void save(JSONObject object)
{
List<YourType> list = new ArrayList<YourType>();
JSONArray array = object.getJSONArray("data")
for(int i=0; i<array.length(); i++)
{
//getObjectFromJson is your method for converting json to an object of your type.
list.add(JsonUtils.fromJson(array.getJSONObject(i).toString(), YourType.class);
}
}
Spring can bind maps and lists of objects if you give create an appropriate class to hold your form data then use the #ModelAttribute annotation on your controller method.
For example, if your JavaScript creates table rows like this:
<tr>
<td><input name="bells[0]" /></td>
<td><input name="whistles[0]" /></td>
</tr>
<tr>
<td><input name="bells[1]" /></td>
<td><input name="whistles[1]" /></td>
</tr>
Then you can create a model class that contains a list for each repeating field in your HTML form, like this:
public class AsapForm {
private List<String> bells;
private List<String> whistles;
// add getters and setters here
}
And then you can create a controller method that uses that class as a parameter with the #ModelAttribute annotation:
public void postAsapForm(#ModelAttribute("contactForm") AsapForm asapForm, BindingResult result) {
...
}
You can then access the values for each row using asapForm.getBells() and asapForm.getWhistles() etc.
I have achieved this using LazyList.
You need to do this in following way.
Operation.java
package com.xxx.xxx.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.list.LazyList;
#Entity
#Table(name="Operations"
,schema="dbo"
)
public class Operations implements java.io.Serializable {
private int operationId;
#Embedded
private Services services;
private String operationName;
private String isHqlsql;
private String isMultipleTables;
private String listOfTablesAffected;
private String hqlQuery;
private String typeOfOperation;
private String operationDetail;
private String inputVariables;
private String outputparamdatatype;
private String isCountQuery;
private String isDynamicWhereQry;
private String isPaginationRequired;
private String biInputParameters;
private List<OperationParameters> operationParameterses = LazyList
.decorate(new ArrayList<OperationParameters>(),
FactoryUtils.instantiateFactory(OperationParameters.class));
public Operations() {
}
public Operations(int operationId, Services services, String operationName) {
this.operationId = operationId;
this.services = services;
this.operationName = operationName;
}
public Operations(int operationId, Services services, String operationName, String isHqlsql, String isMultipleTables, String listOfTablesAffected, String hqlQuery, String typeOfOperation, String operationDetail, String inputVariables, String outputparamdatatype, String isCountQuery, List operationParameterses) {
this.operationId = operationId;
this.services = services;
this.operationName = operationName;
this.isHqlsql = isHqlsql;
this.isMultipleTables = isMultipleTables;
this.listOfTablesAffected = listOfTablesAffected;
this.hqlQuery = hqlQuery;
this.typeOfOperation = typeOfOperation;
this.operationDetail = operationDetail;
this.inputVariables = inputVariables;
this.outputparamdatatype = outputparamdatatype;
this.isCountQuery = isCountQuery;
this.operationParameterses = operationParameterses;
}
#Id
#GeneratedValue
#Column(name="operationId", unique=true, nullable=false)
public int getOperationId() {
return this.operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="serviceId", nullable=false)
public Services getServices() {
return this.services;
}
public void setServices(Services services) {
this.services = services;
}
#Column(name="operationName", nullable=false, length=250)
public String getOperationName() {
return this.operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
#Column(name="isHQLSQL", length=50)
public String getIsHqlsql() {
return this.isHqlsql;
}
public void setIsHqlsql(String isHqlsql) {
this.isHqlsql = isHqlsql;
}
#Column(name="isMultipleTables", length=50)
public String getIsMultipleTables() {
return this.isMultipleTables;
}
public void setIsMultipleTables(String isMultipleTables) {
this.isMultipleTables = isMultipleTables;
}
#Column(name="listOfTablesAffected", length=500)
public String getListOfTablesAffected() {
return this.listOfTablesAffected;
}
public void setListOfTablesAffected(String listOfTablesAffected) {
this.listOfTablesAffected = listOfTablesAffected;
}
#Column(name="hqlQuery")
public String getHqlQuery() {
return this.hqlQuery;
}
public void setHqlQuery(String hqlQuery) {
this.hqlQuery = hqlQuery;
}
#Column(name="typeOfOperation", length=50)
public String getTypeOfOperation() {
return this.typeOfOperation;
}
public void setTypeOfOperation(String typeOfOperation) {
this.typeOfOperation = typeOfOperation;
}
#Column(name="operationDetail")
public String getOperationDetail() {
return this.operationDetail;
}
public void setOperationDetail(String operationDetail) {
this.operationDetail = operationDetail;
}
#Column(name="inputVariables", length=5000)
public String getInputVariables() {
return this.inputVariables;
}
public void setInputVariables(String inputVariables) {
this.inputVariables = inputVariables;
}
#Column(name="outputparamdatatype", length=50)
public String getOutputparamdatatype() {
return this.outputparamdatatype;
}
public void setOutputparamdatatype(String outputparamdatatype) {
this.outputparamdatatype = outputparamdatatype;
}
#Column(name="isCountQuery", length=10)
public String getIsCountQuery() {
return this.isCountQuery;
}
public void setIsCountQuery(String isCountQuery) {
this.isCountQuery = isCountQuery;
}
public String getIsDynamicWhereQry() {
return isDynamicWhereQry;
}
public void setIsDynamicWhereQry(String isDynamicWhereQry) {
this.isDynamicWhereQry = isDynamicWhereQry;
}
public String getIsPaginationRequired() {
return isPaginationRequired;
}
public void setIsPaginationRequired(String isPaginationRequired) {
this.isPaginationRequired = isPaginationRequired;
}
public String getBiInputParameters() {
return biInputParameters;
}
public void setBiInputParameters(String biInputParameters) {
this.biInputParameters = biInputParameters;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="operations")
public List<OperationParameters> getOperationParameterses() {
return this.operationParameterses;
}
public void setOperationParameterses(List<OperationParameters> operationParameterses) {
this.operationParameterses = operationParameterses;
}
}
OperationParameters.java
package com.xxx.xxx.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="OperationParameters"
,schema="dbo"
)
public class OperationParameters implements java.io.Serializable {
private int parameterId;
private Operations operations;
private String inputOutputParamName;
private String inputOutputParamType;
private String inputOutputParamDataType;
public OperationParameters() {
}
public OperationParameters(int parameterId, Operations operations, String inputOutputParamName, String inputOutputParamType, String inputOutputParamDataType) {
this.parameterId = parameterId;
this.operations = operations;
this.inputOutputParamName = inputOutputParamName;
this.inputOutputParamType = inputOutputParamType;
this.inputOutputParamDataType = inputOutputParamDataType;
}
#Id
#GeneratedValue
#Column(name="parameterId", unique=true, nullable=false)
public int getParameterId() {
return this.parameterId;
}
public void setParameterId(int parameterId) {
this.parameterId = parameterId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="operationId", nullable=false)
public Operations getOperations() {
return this.operations;
}
public void setOperations(Operations operations) {
this.operations = operations;
}
#Column(name="inputOutputParamName", nullable=false, length=250)
public String getInputOutputParamName() {
return this.inputOutputParamName;
}
public void setInputOutputParamName(String inputOutputParamName) {
this.inputOutputParamName = inputOutputParamName;
}
#Column(name="inputOutputParamType", nullable=false, length=250)
public String getInputOutputParamType() {
return this.inputOutputParamType;
}
public void setInputOutputParamType(String inputOutputParamType) {
this.inputOutputParamType = inputOutputParamType;
}
#Column(name="inputOutputParamDataType", nullable=false, length=250)
public String getInputOutputParamDataType() {
return this.inputOutputParamDataType;
}
public void setInputOutputParamDataType(String inputOutputParamDataType) {
this.inputOutputParamDataType = inputOutputParamDataType;
}
}
Conroller method to serve the post request to add new Operation.
/**
* Method that will serve the post request to add the operation and operation parameters submitted by the user.
* #param operations
* #param map
* #return {#link String} The view name that will redirect to the get request to display the previous page with newly entered operation in the list.
*/
#RequestMapping(value="/add", method=RequestMethod.POST)
public String addOperations(#ModelAttribute Operations operations, ModelMap map) {
operations.getOperationParameterses().removeAll(Collections.singleton(null));
for(int i=0; i<operations.getOperationParameterses().size(); i++) {
System.out.println("parameterName :: " + ((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName());
if(((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName() == null || "".equalsIgnoreCase((((OperationParameters)operations.getOperationParameterses().get(i))).getInputOutputParamName())) {
operations.getOperationParameterses().remove(i);
System.out.println("empty parameter removed....");
}
}
return "redirect:/operations/" + operations.getServices().getServiceId();
}
Hope this helps you.

Resources