I get the below exception when trying to run an EJB application using TopLink on WebLogic application server.
java.lang.IllegalArgumentException: NamedQuery of name: TblPkgFeature.getFeaturesData not found:
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getDatabaseQuery(EJBQueryImpl.java:422)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:657)
at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.setParameter(EJBQueryImpl.java:202)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weblogic.persistence.InterceptingInvocationHandlerImpl.invoke(InterceptingInvocationHandlerImpl.java:29)
at $Proxy110.setParameter(Unknown Source)
at com.siliconexpert.avago.service.impl.PartDetailServiceImpl.getPackageData(PartDetailServiceImpl.java:170)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:34)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl.getPackageData(Unknown Source)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.ServerRequest.sendReceive(ServerRequest.java:202)
at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:463)
at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:274)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl_12120_WLStub.getPackageData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:84)
at $Proxy111.getPackageData(Unknown Source)
at com.siliconexpert.avago.server.rmi.client.PartDetailServiceRmiClient.getPackageData(PartDetailServiceRmiClient.java:108)
at com.siliconexpert.avago.gui.server.services.PartDetailRemoteServiceImpl.getPackageData(PartDetailRemoteServiceImpl.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at com.siliconexpert.avago.gui.server.services.MainFilter.doFilter(MainFilter.java:47)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3367)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3333)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2220)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2146)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2124)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1564)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)
The above exception is thrown on the below line:
List<TblPkgFeature> list =
em.createNamedQuery("TblPkgFeature.getFeaturesData").setParameter("pkgTypeId", GetFeaturesData.PACKAGE.getCode()).setParameter("type", "package").getResultList();
Also when I changed this method em.createNamedQuery("TblPkgFeature.getFeaturesData") by the method
em.createQuery("select new com.siliconexpert.avago.model.TblPkgFeature(p.fetId, p.fetName, p.fetDisplayName, o.fetDefention, p.unit) " +
" from TblPkgFeature p left outer join p.tblOthersFetDef o where (lower(o.type) =:type or o.type is null )" +
" and p.display=1 and p.pkgTypeId =:pkgTypeId order by p.cmDisplayOrder")
it worked successfully and the exception wasn't thrown.
By the way both queries are the same, but the difference is that I placed the query in the method parameter of the "createQuery()" method.
The below is the entity bean that contains the NamedQuery:
package com.siliconexpert.avago.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* The persistent class for the TBL_PKG_FEATURES database table.
*
*/
#NamedQueries
({
#NamedQuery(name="TblPkgFeature.getFeaturesData", query="select new com.siliconexpert.avago.model.TblPkgFeature(p.fetId, p.fetName, p.fetDisplayName, o.fetDefention, p.unit) " +
" from TblPkgFeature p left outer join p.tblOthersFetDef o where (lower(o.type) =:type or o.type is null )" +
" and p.display=1 and p.pkgTypeId =:pkgTypeId order by p.cmDisplayOrder ") //and p.fetId<>39
})
#Entity
#Table(name = "TBL_PKG_FEATURES")
public class TblPkgFeature implements Serializable
{
private static final long serialVersionUID = -8604710446605212000L;
#Id
#Column(name = "FET_ID")
private long fetId;
#Column(name = "CM_DISPLAY_ORDER")
private long cmDisplayOrder;
#Column(name = "DATA_LENGHT")
private long dataLenght;
#Column(name = "DATA_TYPE")
private String dataType;
private long display;
#Column(name = "FET_DISPLAY_NAME")
private String fetDisplayName;
#Column(name = "FET_HEADER_ORDER")
private long fetHeaderOrder;
#Column(name = "FET_NAME")
private String fetName;
#Column(name = "OLD_NAME")
private String oldName;
#Column(name = "PKG_TYPE_ID")
private long pkgTypeId;
#Column(name = "QUALITY_AV")
private long qualityAv;
#Column(name = "TBL_NAME")
private String tblName;
private String unit;
#OneToOne
#JoinColumn(name="FET_NAME", referencedColumnName="FET_NAME", updatable=false, insertable=false)
private TblOthersFetDef tblOthersFetDef;
#Transient
private String fetDefinition;
public TblPkgFeature()
{
}
public TblPkgFeature(long fetId, String fetDisplayName)
{
super();
this.fetId = fetId;
this.fetDisplayName = fetDisplayName;
}
public TblOthersFetDef getTblOthersFetDef()
{
return tblOthersFetDef;
}
public void setTblOthersFetDef(TblOthersFetDef tblOthersFetDef)
{
this.tblOthersFetDef = tblOthersFetDef;
}
public TblPkgFeature(long fetId, String fetDisplayName, String fetDefinition, String unit)
{
this(fetId, fetDisplayName);
this.fetDefinition = fetDefinition;
this.unit = unit;
}
public TblPkgFeature(long fetId, String fetName, String fetDisplayName, String fetDefinition, String unit)
{
this(fetId, fetDisplayName, fetDefinition, unit);
this.fetName = fetName;
}
public String getFetDefinition()
{
return fetDefinition;
}
public void setFetDefinition(String fetDefinition)
{
this.fetDefinition = fetDefinition;
}
public long getFetId()
{
return this.fetId;
}
public void setFetId(long fetId)
{
this.fetId = fetId;
}
public long getCmDisplayOrder()
{
return this.cmDisplayOrder;
}
public void setCmDisplayOrder(long cmDisplayOrder)
{
this.cmDisplayOrder = cmDisplayOrder;
}
public long getDataLenght()
{
return this.dataLenght;
}
public void setDataLenght(long dataLenght)
{
this.dataLenght = dataLenght;
}
public String getDataType()
{
return this.dataType;
}
public void setDataType(String dataType)
{
this.dataType = dataType;
}
public long getDisplay()
{
return this.display;
}
public void setDisplay(long display)
{
this.display = display;
}
public String getFetDisplayName()
{
return this.fetDisplayName;
}
public void setFetDisplayName(String fetDisplayName)
{
this.fetDisplayName = fetDisplayName;
}
public long getFetHeaderOrder()
{
return this.fetHeaderOrder;
}
public void setFetHeaderOrder(long fetHeaderOrder)
{
this.fetHeaderOrder = fetHeaderOrder;
}
public String getFetName()
{
return this.fetName;
}
public void setFetName(String fetName)
{
this.fetName = fetName;
}
public String getOldName()
{
return this.oldName;
}
public void setOldName(String oldName)
{
this.oldName = oldName;
}
public long getPkgTypeId()
{
return this.pkgTypeId;
}
public void setPkgTypeId(long pkgTypeId)
{
this.pkgTypeId = pkgTypeId;
}
public long getQualityAv()
{
return this.qualityAv;
}
public void setQualityAv(long qualityAv)
{
this.qualityAv = qualityAv;
}
public String getTblName()
{
return this.tblName;
}
public void setTblName(String tblName)
{
this.tblName = tblName;
}
public String getUnit()
{
return this.unit;
}
public void setUnit(String unit)
{
this.unit = unit;
}
}
Please help.
Thanks.
Related
I read many articles but still my problem is continuing, while fetching data from firebase as list. could you please help me on this.
Error: com.google.firebase.database.DatabaseException: Can't convert
object of type java.lang.String to type SubCategoryLoad Object
Firebase database image
--> Loading data from firebase:
mSubCategoryDatabaseRef = FirebaseDatabase.getInstance().getReference("user_post_add_database_ref").child("yeswanth599").child(mCategoryNameReceive);
mSubCategoryDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
GenericTypeIndicator<Map<String,SubCategoryLoad>> genericTypeIndicator=new GenericTypeIndicator<Map<String,SubCategoryLoad>>(){};
(-->Error Showing in this Line) Map<String,SubCategoryLoad> map=(Map<String, SubCategoryLoad>)postSnapshot.getValue(genericTypeIndicator);
assert map != null;
mSubCategoryLoad=new ArrayList<>(map.values());
}
mSubCategoryAdapter = new SubCategoryDisplayAdapter(getContext(), mSubCategoryLoad);
mSubCategoryRecyclerView.setAdapter(mSubCategoryAdapter);
mSubCategoryProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mSubCategoryProgressCircle.setVisibility(View.INVISIBLE);
}
});
--> SubCategoryLoad.Class
public class SubCategoryLoad {
private String mUserPostAddress;
private String mUserPostBusinessEndTime;
private String mUserPostBusinessSelectedCity;
private String mUserPostBusinessSelectedCountry;
private String mUserPostBusinessStartTime;
private String mUserPostCategory;
private String mUserPostEmail;
private List<UserPostAdsImages> mUserPostImages;
private String mUserPostName;
private String mUserPostPhonenumber;
private List<UserPostAdsLanguages> mUserPostSupportingLanguage;
private String mUserPostWebsite;
public SubCategoryLoad() {
//empty constructor needed
}
public SubCategoryLoad(String userPostAddress, String userPostBusinessEndTime,
String userPostBusinessSelectedCity, String userPostBusinessSelectedCountry,
String userPostBusinessStartTime, String userPostCategory,
String userPostEmail, List<UserPostAdsImages> userPostImages,
String userPostName, String userPostPhonenumber,
List<UserPostAdsLanguages> userPostSupportingLanguage, String userPostWebsite
) {
mUserPostAddress = userPostAddress;
mUserPostBusinessEndTime = userPostBusinessEndTime;
mUserPostBusinessSelectedCity = userPostBusinessSelectedCity;
mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry;
mUserPostBusinessStartTime = userPostBusinessStartTime;
mUserPostCategory = userPostCategory;
mUserPostEmail = userPostEmail;
mUserPostImages = userPostImages;
mUserPostName = userPostName;
mUserPostPhonenumber = userPostPhonenumber;
mUserPostSupportingLanguage = userPostSupportingLanguage;
mUserPostWebsite = userPostWebsite;
}
public void setUserPostAddress(String userPostAddress) {
this.mUserPostAddress = userPostAddress;
}
public void setUserPostBusinessEndTime(String userPostBusinessEndTime) {
this.mUserPostBusinessEndTime = userPostBusinessEndTime;
}
public void setUserPostBusinessSelectedCity(String userPostBusinessSelectedCity) {
this.mUserPostBusinessSelectedCity = userPostBusinessSelectedCity;
}
public void setUserPostBusinessSelectedCountry(String userPostBusinessSelectedCountry) {
this.mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry;
}
public void setUserPostBusinessStartTime(String userPostBusinessStartTime) {
this.mUserPostBusinessStartTime = userPostBusinessStartTime;
}
public void setUserPostCategory(String userPostCategory) {
this.mUserPostCategory = userPostCategory;
}
public void setUserPostEmail(String userPostEmail) {
this.mUserPostEmail = userPostEmail;
}
public void setUserPostImages(List<UserPostAdsImages> userPostImages) {
this.mUserPostImages = userPostImages;
}
public void setUserPostName(String userPostName) {
this.mUserPostName = userPostName;
}
public void setUserPostPhonenumber(String userPostPhonenumber) {
this.mUserPostPhonenumber = userPostPhonenumber;
}
public void setUserPostSupportingLanguage(List<UserPostAdsLanguages> userPostSupportingLanguage) {
this.mUserPostSupportingLanguage = userPostSupportingLanguage;
}
public void setUserPostWebsite(String userPostWebsite) {
this.mUserPostWebsite = userPostWebsite;
}
public String getUserPostAddress() {
return mUserPostAddress;
}
public String getUserPostBusinessEndTime() {
return mUserPostBusinessEndTime;
}
public String getUserPostBusinessSelectedCity() {
return mUserPostBusinessSelectedCity;
}
public String getUserPostBusinessSelectedCountry() {
return mUserPostBusinessSelectedCountry;
}
public String getUserPostBusinessStartTime() {
return mUserPostBusinessStartTime;
}
public String getUserPostCategory() {
return mUserPostCategory;
}
public String getUserPostEmail() {
return mUserPostEmail;
}
public List<UserPostAdsImages> getUserPostImages() {
return mUserPostImages;
}
public String getUserPostName() {
return mUserPostName;
}
public String getUserPostPhonenumber() {
return mUserPostPhonenumber;
}
public List<UserPostAdsLanguages> getUserPostSupportingLanguage() {
return mUserPostSupportingLanguage;
}
public String getUserPostWebsite() {
return mUserPostWebsite;
}
}
--> SubCategoryDisplayAdapter.class
SubCategoryLoad subCategoryLoadCurrent = mSubCategoryLoad.get(position);
holder.mSubCategoryAdsTitle.setText(subCategoryLoadCurrent.getUserPostName());
holder.mSubCategoryAdsSupportingLanguagesList.setText("English,Japanese");
//Log.i(TAG, "message:"+subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList());
Glide.with(mContext)
.load(subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList())
.into(holder.mSubCategoryAdsImage);
Thanks & Regards,
Yeswanth.
I used to have the same issue with my parsing and the problem was instead of a list of custom objects i was supposed to be using a Map like this
private Map<String,Boolean>
That field in Firebase contains a key and a state (True or False).
Also you can check the code on the docs to see how they parse these objects.
https://firebase.google.com/docs/database/android/read-and-write?authuser=0#read_data_once
i have html form which i forward to spring controller. Its works fine if i use getParameter but using modelAttribute it says 400 bad request error.
Here is my controller Code
#Controller
public class BookController {
#RequestMapping (value="/addBook")
public String addBook(#ModelAttribute Book book){
System.out.println(book.getBookName());
bookService.addBooks(book);
return "index";
}
}
This is Book model Code
#Entity
#Table (name = "Book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID",columnDefinition = "BIGINT NOT NULL AUTO_INCREMENT")
private long bookId;
#Column(name="book_code",columnDefinition = "VARCHAR(200) NOT NULL")
private String bookCode;
private String bookName;
private String author;
#Temporal (TemporalType.DATE)
private Date dateOfArrival;
private Double price;
private String rackNo;
private int numberOfBook;
private String subjectCode;
public Book() {
super();
}
public Book(String bookCode, String bookName, String author,
Date dateOfArrival, Double price, String rackNo,
int numberOfBook, String subjectCode) {
super();
this.bookCode = bookCode;
this.bookName = bookName;
this.author = author;
this.dateOfArrival = dateOfArrival;
this.price = price;
this.rackNo = rackNo;
this.numberOfBook = numberOfBook;
this.subjectCode = subjectCode;
}
public String getBookCode() {
return bookCode;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDateOfArrival() {
return dateOfArrival;
}
public void setDateOfArrival(Date dateOfArrival) {
this.dateOfArrival = dateOfArrival;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRackNo() {
return rackNo;
}
public void setRackNo(String rackNo) {
this.rackNo = rackNo;
}
public int getNumberOfBook() {
return numberOfBook;
}
public void setNumberOfBook(int numberOfBook) {
this.numberOfBook = numberOfBook;
}
public String getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(String subjectCode) {
this.subjectCode = subjectCode;
}
}
I have doubt that the problem is due to using date
Please Help me out
I would try 2 things.
In your Model add this:
//here use the same pattern of date your send from the view
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dateOfArrival;
In your controller
#RequestMapping (value="/addBook")
public String addBook(#ModelAttribute Book book, BindingResult result){
...
Then you will be able to debug your method and know the problem.
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.
I'm trying to persist a record that has a mapped #Persistent InputStream field.
the context is: JDK 1.8, LiferayPortal on Tomee 1.7.1 (OpenJPA 2.4-patch). Sorry about the stacktrace polluted by the Liferay one.
#Entity
#Table(name = "file_entries")
public class FileEntry implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(length = 120)
private String createdBy;
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Column(length = 120)
private String modifiedBy;
#Temporal(TemporalType.TIMESTAMP)
private Date modified;
#Column(length = 200)
private String title;
#Column(length = 2000)
private String description;
#Column(length = 240)
private String filename;
#Column(length = 60)
private String extension;
#Column(length = 20)
private String version;
#Column(length = 240)
private String contentType;
#Persistent(fetch = FetchType.LAZY)
private InputStream content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public InputStream getContent() {
return content;
}
public void setContent(InputStream content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
And when persisting:
logo = new FileEntry();
logo.setContent(new FileInputStream("some_local_file"));
entityService.persist(logo);
I get the following exception.
<openjpa-2.4.0-nonfinal-1598334-r422266:1599166 fatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction has been rolled back. See the nested exceptions for details on the errors that occurred.
at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2370)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2207)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2105)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1876)
at org.apache.openjpa.kernel.DelegatingBroker.flush(DelegatingBroker.java:1045)
at org.apache.openjpa.persistence.EntityManagerImpl.flush(EntityManagerImpl.java:663)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.zeroturnaround.jrebel.integration.openjpa.EntityManagerFactoryWrapper$ReloadingMethodHandler.invoke(EntityManagerFactoryWrapper.java:135)
at com.sun.proxy.$Proxy619.flush(Unknown Source)
at org.apache.openejb.persistence.JtaEntityManager.flush(JtaEntityManager.java:202)
at com.computas.generic.service.SimpleEntityService.persist(SimpleEntityService.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
at sun.reflect.GeneratedMethodAccessor585.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:227)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:194)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:308)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:303)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:308)
... 171 more
Caused by: <openjpa-2.4.0-nonfinal-1598334-r422266:1599166 fatal general error> org.apache.openjpa.persistence.PersistenceException: can't call setAutoCommit when the connection is JtaManaged
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4998)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4958)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:134)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:108)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:60)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:185)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:96)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:77)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:732)
at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:131)
... 204 more
Caused by: java.sql.SQLException: can't call setAutoCommit when the connection is JtaManaged
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.forbiddenCall(ManagedConnection.java:185)
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.invokeUnderTransaction(ManagedConnection.java:162)
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.invoke(ManagedConnection.java:93)
at com.sun.proxy.$Proxy618.setAutoCommit(Unknown Source)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.ConfiguringConnectionDecorator$ConfiguringConnection.setAutoCommit(ConfiguringConnectionDecorator.java:117)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.jdbc.sql.PostgresDictionary.insertPostgresBlob(PostgresDictionary.java:627)
at org.apache.openjpa.jdbc.sql.PostgresDictionary.insertBlobForStreamingLoad(PostgresDictionary.java:614)
at org.apache.openjpa.jdbc.meta.strats.LobFieldStrategy.insert(LobFieldStrategy.java:100)
at org.apache.openjpa.jdbc.meta.FieldMapping.insert(FieldMapping.java:623)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.insert(AbstractUpdateManager.java:238)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:165)
... 208 more
The persistence unit declaration is:
<persistence-unit name="uefiscdi" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>uefiscdiDS</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<property name="openjpa.jdbc.DBDictionary" value="postgres" />
<property name="openjpa.Log" value="DefaultLevel=INFO, Tool=INFO" />
</properties>
</persistence-unit>
The Datasource declaration is:
<Resource id="uefiscdiDS" type="DataSource">
JdbcDriver org.postgresql.Driver
JdbcUrl jdbc:postgresql://localhost:5432/db_name
UserName user_name
Password user_password
JtaManaged true
DefaultAutoCommit false
</Resource>
I tried with DefaultAutoCommit true / false / not declared ... same exception.
Just a shot in the dark, but have you tried calling em.persist(...) rather than em.merge(..)?
If that doesn't work it might be helpful if you posted the full stack trace somewhere. I'm afraid you might have snipped off the important parts.
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.