association query issue - ibatis

I'm using mybatis , I encounter a association query issue, pls take a look at table structures first.
DROP TABLE IF EXISTS `comp_items_spec`;
CREATE TABLE `comp_items_spec` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`comp_id` int(11) NOT NULL,
`content_type_id` int(11) NOT NULL,
`in_list_flag` char(1) DEFAULT NULL,
`label` varchar(200) DEFAULT NULL,
`static_flag` char(1) DEFAULT NULL,
`ext1_name` varchar(200) DEFAULT NULL,
`ext1_value` text,
`ext2_name` varchar(200) DEFAULT NULL,
`ext2_value` text,
`ext3_name` varchar(200) DEFAULT NULL,
`ext3_value` text,
`ext4_name` varchar(200) DEFAULT NULL,
`ext4_value` text,
`ext5_name` varchar(200) DEFAULT NULL,
`ext5_value` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;
/*Data for the table `comp_items_spec` */
insert into `comp_items_spec`(`id`,`comp_id`,`content_type_id`,`in_list_flag`,`label`,`static_flag`,`ext1_name`,`ext1_value`,`ext2_name`,`ext2_value`,`ext3_name`,`ext3_value`,`ext4_name`,`ext4_value`,`ext5_name`,`ext5_value`) values (43,22,1,'\0','description','Y','description','description1......',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),(44,22,3,'\0','static image','Y',NULL,'http://img3.cache.netease.com/cnews/2012/12/6/20121206092637ba11c.jpg',NULL,'501',NULL,'425',NULL,NULL,NULL,NULL);
/*Table structure for table `components_spec` */
DROP TABLE IF EXISTS `components_spec`;
CREATE TABLE `components_spec` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) DEFAULT NULL,
`show_latest_num` int(11) DEFAULT NULL,
`more_link_url` varchar(200) DEFAULT NULL,
`more_link_flag` char(1) DEFAULT NULL,
`open_in_new_flag` char(1) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`update_date` datetime DEFAULT NULL,
`creator_sso` varchar(20) DEFAULT NULL,
`updator_sso` varchar(20) DEFAULT NULL,
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1;
/*Data for the table `components_spec` */
insert into `components_spec`(`id`,`name`,`show_latest_num`,`more_link_url`,`more_link_flag`,`open_in_new_flag`,`create_date`,`update_date`,`creator_sso`,`updator_sso`) values (22,'Banner',5,'more.blog.ge.com','Y','Y','2012-12-08 21:30:58','2012-12-08 21:30:58','502156886','502156886');
the relationship between components_spec and comp_items_spec is 1:N,comp_items_spec has two kind of data ,dynamic items and static items which are distinguish from column static_flag, it's dynamic items when static_flag='N', and I also define bean ComponentSpec and CompItemSpec to map the entity. pls see the source code from below:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ComponentSpec {
private int id;
private String name;
private int showLatestNum;
private String moreLinkUrl;
private char moreLinkFlag;
private char openInNewFlag;
private Date createDate;
private Date updateDate;
private String creatorSSO;
private String updatorSSO;
private List<CompItemSpec> staticItemSpecList =new ArrayList<CompItemSpec>();
private List<CompItemSpec> dynamicItemSpecList =new ArrayList<CompItemSpec>();
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getMoreLinkFlag() {
return moreLinkFlag;
}
public void setMoreLinkFlag(char moreLinkFlag) {
this.moreLinkFlag = moreLinkFlag;
}
public String getMoreLinkUrl() {
return moreLinkUrl;
}
public void setMoreLinkUrl(String moreLinkUrl) {
this.moreLinkUrl = moreLinkUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getShowLatestNum() {
return showLatestNum;
}
public void setShowLatestNum(int showLatestNum) {
this.showLatestNum = showLatestNum;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public char getOpenInNewFlag() {
return openInNewFlag;
}
public void setOpenInNewFlag(char openInNewFlag) {
this.openInNewFlag = openInNewFlag;
}
public List<CompItemSpec> getStaticItemSpecList() {
return staticItemSpecList;
}
public void addStaticItemSpec(CompItemSpec compStaticItemSpec){
getStaticItemSpecList().add(compStaticItemSpec);
compStaticItemSpec.setComponentSpec(this);
}
public List<CompItemSpec> getDynamicItemSpecList() {
return dynamicItemSpecList;
}
public void addDynamicItemSpec(CompItemSpec dynamicItemSpec){
getDynamicItemSpecList().add(dynamicItemSpec);
dynamicItemSpec.setComponentSpec(this);
}
public String getCreatorSSO() {
return creatorSSO;
}
public void setCreatorSSO(String creatorSSO) {
this.creatorSSO = creatorSSO;
}
public String getUpdatorSSO() {
return updatorSSO;
}
public void setUpdatorSSO(String updatorSSO) {
this.updatorSSO = updatorSSO;
}
}
public class CompItemSpec {
private int id;
private int compId;
private int contentTypeId;
private char inListFlag;
private char staticFlag;
private String label;
private String ext1Name;
private String ext1Value;
private String ext2Name;
private String ext2Value;
private String ext3Name;
private String ext3Value;
private String ext4Name;
private String ext4Value;
private String ext5Name;
private String ext5Value;
private ComponentSpec componentSpec;
public int getCompId() {
return compId;
}
public void setCompId(int compId) {
this.compId = compId;
}
public String getExt1Name() {
return ext1Name;
}
public void setExt1Name(String ext1Name) {
this.ext1Name = ext1Name;
}
public String getExt1Value() {
return ext1Value;
}
public void setExt1Value(String ext1Value) {
this.ext1Value = ext1Value;
}
public String getExt2Name() {
return ext2Name;
}
public void setExt2Name(String ext2Name) {
this.ext2Name = ext2Name;
}
public String getExt2Value() {
return ext2Value;
}
public void setExt2Value(String ext2Value) {
this.ext2Value = ext2Value;
}
public String getExt3Name() {
return ext3Name;
}
public void setExt3Name(String ext3Name) {
this.ext3Name = ext3Name;
}
public String getExt3Value() {
return ext3Value;
}
public void setExt3Value(String ext3Value) {
this.ext3Value = ext3Value;
}
public String getExt4Name() {
return ext4Name;
}
public void setExt4Name(String ext4Name) {
this.ext4Name = ext4Name;
}
public String getExt4Value() {
return ext4Value;
}
public void setExt4Value(String ext4Value) {
this.ext4Value = ext4Value;
}
public String getExt5Name() {
return ext5Name;
}
public void setExt5Name(String ext5Name) {
this.ext5Name = ext5Name;
}
public String getExt5Value() {
return ext5Value;
}
public void setExt5Value(String ext5Value) {
this.ext5Value = ext5Value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getContentTypeId() {
return contentTypeId;
}
public void setContentTypeId(int contentTypeId) {
this.contentTypeId = contentTypeId;
}
public char getInListFlag() {
return inListFlag;
}
public void setInListFlag(char inListFlag) {
this.inListFlag = inListFlag;
}
public char getStaticFlag() {
return staticFlag;
}
public void setStaticFlag(char staticFlag) {
this.staticFlag = staticFlag;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public ComponentSpec getComponentSpec() {
return componentSpec;
}
public void setComponentSpec(ComponentSpec componentSpec) {
this.componentSpec = componentSpec;
}
}
sqlmap is like below:
<mapper namespace="com.ge.dao.ComponentSpecMapper">
<resultMap id="componentMap" type="componentSpec">
<id column="id" property="id"/>
<result column="temp_id" property="tempId"/>
<result column="show_latest_num" property="showLatestNum"/>
<result column="more_link_url" property="moreLinkUrl"/>
<result column="more_link_flag" property="moreLinkFlag"/>
<result column="open_in_new_flag" property="openInNewFlag"/>
<result column="update_date" property="updateDate"/>
<result column="create_date" property="createDate"/>
<result column="updator_sso" property="updatorSSO"/>
<result column="creator_sso" property="creatorSSO"/>
<collection property="staticItemSpecList" ofType="itemSpec">
<id column="static_item_id" property="id"/>
<result column="id" property="compId"/>
<result column="static_content_type_id" property="contentTypeId"/>
<result column="static_label" property="label"/>
<result column="static_ext1_value" property="ext1Value"/>
<result column="static_ext2_value" property="ext2Value"/>
<result column="static_ext3_value" property="ext3Value"/>
<result column="static_ext4_value" property="ext4Value"/>
<result column="static_ext5_value" property="ext5Value"/>
</collection>
<collection property="dynamicItemSpecList" ofType="itemSpec">
<id column="dynamic_item_id" property="id"/>
<result column="id" property="compId"/>
<result column="dynamic_content_type_id" property="contentTypeId"/>
<result column="dynamic_in_list_flag" property="inListFlag"/>
<result column="dynamic_label" property="label"/>
<result column="dynamic_ext1_value" property="ext1Value"/>
<result column="dynamic_ext2_value" property="ext2Value"/>
<result column="dynamic_ext3_value" property="ext3Value"/>
<result column="dynamic_ext4_value" property="ext4Value"/>
<result column="dynamic_ext5_value" property="ext5Value"/>
</collection>
</resultMap>
<sql id="compSpecMain">
SELECT
comp.id,
comp.name,
show_latest_num,
more_link_url,
more_link_flag,
open_in_new_flag,
create_date,
update_date,
creator_sso,
updator_sso,
si.id static_item_id,
si.content_type_id static_content_type_id,
si.in_list_flag static_in_list_flag,
si.label static_label,
si.ext1_value static_ext1_value,
si.ext2_value static_ext2_value,
si.ext3_value static_ext3_value,
si.ext4_value static_ext4_value,
si.ext5_value static_ext5_value,
di.id dynamic_item_id,
di.content_type_id dynamic_content_type_id,
di.in_list_flag dynamic_in_list_flag,
di.label dynamic_label,
di.ext1_value dynamic_ext1_value,
di.ext2_value dynamic_ext2_value,
di.ext3_value dynamic_ext3_value,
di.ext4_value dynamic_ext4_value,
di.ext5_value dynamic_ext5_value
FROM components_spec comp
LEFT JOIN comp_items_spec si ON si.comp_id=comp.id AND si.static_flag='Y'
LEFT JOIN comp_items_spec di ON di.comp_id=comp.id AND di.static_flag='N'
</sql>
<select id="selectComponentSpecByID" parameterType="int" resultMap="componentMap">
<include refid="compSpecMain"/>
WHERE
comp.id=#{id}
</select>
<select id="selectComponentSpecByName" parameterType="string" resultMap="componentMap">
<include refid="compSpecMain"/>
WHERE
comp.name like #{name}
</select>
the issue here is when I do the selectComponentSpecByID query, the dynamic item list is supposed has nothing , but actual result is two elements, I think it's a problem with result map definition, but no glue. any suggestions? thanks .

finally I found the solution by myself, because when id property is null ,meaning no records retrieved in the result, mybatis still compare them and treat them as valid result and put them into sub list,that's the reason, to fix it,just define notNullColumn of Collection element preventing null id. Done!
<resultMap id="componentMap" type="componentSpec">
<id column="id" property="id"/>
<result column="temp_id" property="tempId"/>
<result column="show_latest_num" property="showLatestNum"/>
<result column="more_link_url" property="moreLinkUrl"/>
<result column="more_link_flag" property="moreLinkFlag"/>
<result column="open_in_new_flag" property="openInNewFlag"/>
<result column="update_date" property="updateDate"/>
<result column="create_date" property="createDate"/>
<result column="updator_sso" property="updatorSSO"/>
<result column="creator_sso" property="creatorSSO"/>
<collection property="staticItemSpecList" notNullColumn="static_item_id" ofType="itemSpec">
<id column="static_item_id" property="id"/>
<result column="id" property="compId"/>
<result column="static_content_type_id" property="contentTypeId"/>
<result column="static_label" property="label"/>
<result column="static_ext1_value" property="ext1Value"/>
<result column="static_ext2_value" property="ext2Value"/>
<result column="static_ext3_value" property="ext3Value"/>
<result column="static_ext4_value" property="ext4Value"/>
<result column="static_ext5_value" property="ext5Value"/>
</collection>
<collection property="dynamicItemSpecList" notNullColumn="dynamic_item_id" ofType="itemSpec">
<id column="dynamic_item_id" property="id"/>
<result column="id" property="compId"/>
<result column="dynamic_content_type_id" property="contentTypeId"/>
<result column="dynamic_in_list_flag" property="inListFlag"/>
<result column="dynamic_label" property="label"/>
<result column="dynamic_ext1_value" property="ext1Value"/>
<result column="dynamic_ext2_value" property="ext2Value"/>
<result column="dynamic_ext3_value" property="ext3Value"/>
<result column="dynamic_ext4_value" property="ext4Value"/>
<result column="dynamic_ext5_value" property="ext5Value"/>
</collection>
</resultMap>

Related

Struts2 execAndWait and file upload no work

I have this problem and I'm really going crazy without having a result.
I have a form and all fields are required through validator.xml
My form contains a field for the upload image (required)
When I click the submit button present a paggina waiting through (execAndWait configured in struts.xml).
my big problem is this:
the waiting page always redirect to my form page with text (the file field and mandatory).
Here is the code:
/register.jsp
<!-- al submit chiama l'action register -->
<action name="register" class="action.Register" method="execute" >
<interceptor-ref name="defaultStack" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">10000000</param>
<param name="allowedTypes">image/jpeg,image/gif,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="params"></interceptor-ref>
<interceptor-ref name="execAndWait">
</interceptor-ref>
<result name="success">index.jsp</result>
<result name="input">/register.jsp</result>
<result name="wait">/test.jsp</result>
</action>
waiting page:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/>
</head>
<body>
<p>your request is processing...</p>
<img src="images/indicator.gif"/>
my form:
<s:form method="post" action="register" validate="false" enctype="multipart/form-data">
<s:textfield key="utenteBean.nome" name="utenteBean.nome" value="a" />
<s:textfield key="utenteBean.nickname" name="utenteBean.nickname" value="a" />
<sj:datepicker key="utenteBean.nato" name="utenteBean.nato"
showButtonPanel="true" displayFormat="dd/mm/yy" value="25/09/1983"/>
<s:textfield key="utenteBean.professione" name="utenteBean.professione" value="a"/>
<s:textfield key="utenteBean.eta" name="utenteBean.eta" value="3"/>
<s:textfield key="utenteBean.dj_preferito" name="utenteBean.dj_preferito" value="a" />
<s:textfield key="utenteBean.rave_fatti" name="utenteBean.rave_fatti" value="3" />
<s:textfield key="utenteBean.sito_preferito" name="utenteBean.sito_preferito" value="a" />
<s:textfield key="utenteBean.come_siveste" name="utenteBean.come_siveste" value="a" />
<s:textarea key="utenteBean.messaggio" name="utenteBean.messaggio" value="a"/>
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
really thanks for your help
I suppose that you have put wrong field name for the file tag. Can you show us your action class? Regarding to that instead of:
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
try to use:
<s:file label="file" name="utenteBean.file" requiredLabel="true"" ></s:file>
or just check in your action class the name of the file property.
yes sure ... below my Action class:
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private File file;
private String fileContentType;
private String fileFileName;
private String filesPath;
private ServletContext context;
Map<String, Object> session;
public String execute(){
if (file != null) {
File file = this.file;
// /System.out.println(file.getName());
try {
Util.saveFile(file, fileFileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate(){
if(this.fileFileName==null){
this.addFieldError("file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
Thank you so much for your help ...
I solved it by putting my bean in session. I could not find a better solution after many hours of work.
If other people have the same problem I can see the changes I made in my. Action
package action;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import Bean.UtenteBeanAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import Utility.Util;
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private ServletContext context;
Map<String, Object> session;
public String execute(){
session.put("utente", utenteBean);
if (utenteBean.getFile() != null) {
File file = utenteBean.getFile();
// /System.out.println(file.getName());
try {
Util.saveFile(file, utenteBean.getFileFileName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate() {
if (session.get("utente") != null) {
this.utenteBean = (UtenteBeanAction) session.get("utente");
}
if (this.utenteBean.getFileFileName() == null) {
this.addFieldError("utenteBean.file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
I hope I can be of help.
Thanks for the support.

org.apache.solr.client.solrj.beans.BindingException

I have the below bean class for defining my solrInputDocument
public class VenueDocumentSolr extends SolrInputDocument {
#Field
private int id;
#Field
private String uid;
...
}
And I try to get the results using the below code:
SolrQuery query = new SolrQuery();
query.setQuery(SearchForRestaurants);
QueryResponse rsp = SolrUtil.issueSolrQuery(query);
for (SolrDocument s : rsp.getResults())
System.out.println(s);
List<VenueDocumentSolr> beans = rsp.getBeans(VenueDocumentSolr.class);
the above code works sometimes and throws the below Exception rest of the time.
I cross checked and added missing fields to my bean class. But of no use. I still get the error :(
org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object of class com.zvents.common.entities.solr.VenueDocumentSolr
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:68)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBeans(DocumentObjectBinder.java:47)
at org.apache.solr.client.solrj.response.QueryResponse.getBeans(QueryResponse.java:480)
at com.zvents.webapp.api.DeleteData.QueryAndUpdateVenuesForSearch(DeleteData.java:117)
.........
Quoting a part of the Schema
<int name="has_images">*</int>
<arr name="cuisine">
<str>*</str>
</arr>
<arr name="venue_type">
<int>*</int>
</arr>
<double name="location_0_latLon">*</double>
<float name="venue_imp">*</float>
<date name="last_indexed">*</date>
Quoting applicable fields from bean class
#Field
private int has_images;
#Field
private List<String> cuisine;
#Field
private List<Integer> venue_type;
#Field
private double location_0_latLon;
#Field
private float venue_imp;
#Field
private String last_indexed;
I did it in following way:
DocumentObjectBinder binder = new DocumentObjectBinder();
beanlist = binder.getBeans(PortalBean.class, list);
package hello;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.beans.DocumentObjectBinder;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SearchOnNameController {
#CrossOrigin(origins = "*")
#RequestMapping("search")
public List<PortalBean> searchName(#RequestParam(value = "query", defaultValue = "*") String name) {
String urlString = "http://localhost:8983/solr/kislay";
SolrClient solr = new HttpSolrClient(urlString);
SolrQuery query = new SolrQuery();
// query.addField("name");
query.setQuery("name:" + "*" + name + "*");
PortalBean bean = null;
List<PortalBean> beanlist = new ArrayList<PortalBean>();
try {
QueryResponse response = solr.query(query);
SolrDocumentList list = response.getResults();
DocumentObjectBinder binder = new DocumentObjectBinder();
beanlist = binder.getBeans(PortalBean.class, list);
} catch (SolrServerException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return beanlist;
}
}
The bean is mapped as :
package hello;
import org.apache.lucene.document.TextField;
import org.apache.solr.client.solrj.beans.Field;
import org.apache.solr.schema.StrField;
public class PortalBean {
private String id;
private String name;
private String image;
private String description;
private String branding;
private double rating;
private double setup_fee;
private String transaction_fees;
private String how_to_url;
private String [] currencies;
public String getId() {
return id;
}
#Field("id")
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
#Field("name")
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
#Field("image")
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
#Field("description")
public void setDescription(String description) {
this.description = description;
}
public String getBranding() {
return branding;
}
#Field("branding")
public void setBranding(String branding) {
this.branding = branding;
}
public double getRating() {
return rating;
}
#Field("rating")
public void setRating(double rating) {
this.rating = rating;
}
public double getSetup_fee() {
return setup_fee;
}
#Field("setup_fee")
public void setSetup_fee(double setup_fee) {
this.setup_fee = setup_fee;
}
public String getTransaction_fees() {
return transaction_fees;
}
#Field("transaction_fees")
public void setTransaction_fees(String transaction_fees) {
this.transaction_fees = transaction_fees;
}
public String getHow_to_url() {
return how_to_url;
}
#Field("how_to_url")
public void setHow_to_url(String how_to_url) {
this.how_to_url = how_to_url;
}
public String [] getCurrencies() {
return currencies;
}
#Field("currencies")
public void setCurrencies(String [] currencies) {
this.currencies = currencies;
}
}
Also please note that managed-schema file need to have proper definition of the fields:
example as per my use case:
<field name="branding" type="string"/>
<field name="currencies" type="strings"/>
<field name="description" type="string"/>
<field name="how_to_url" type="string"/>
<field name="id" type="string" multiValued="false" indexed="true" required="true" stored="true"/>
<field name="image" type="string"/>
<field name="name" type="string"/>
<field name="rating" type="tdouble"/>
<field name="setup_fee" type="tdouble"/>
<field name="transaction_fee" type="string"/>
Unfortunately you do not post all of your pojo and all of your schema, so I can only guess.
The only thing I see, from the code you posted is that you are trying to let solr do some sort of conversion for you.
That is for
#Field
private String last_indexed;
And
<date name="last_indexed">*</date>
Solr will not convert a Date to a String for you, just will not. But without a full schema and the full code of your Bean, I cannot give you a full answer.
Other things I noted from the code you post
why are you putting * within the elements of your schema as far as I know that does not have any effect
why are you extending SolrInputDocument? You do not need to. #Field is designed so that you do not need to subclass anything, but may use your model's POJOs right away.
My error was: BindingException: Could not instantiate object
I added a no variable constructor to the POJO and it started to work.
public class MyItem {
String id;
#Field("id")
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public MyItem() {
}
}
To get to here the only fields in my schema were:
<field name="_version_" type="long" indexed="true" stored="true"/>
<field name="_root_" type="string" indexed="true" stored="false"/>
<field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<field name="text" type="string" indexed="true" stored="false" multiValued="true"/>
<uniqueKey>id</uniqueKey>
This is the code to dump the ids in the solr.
private void dumpSolr2() throws SolrServerException {
System.out.println("dumpSolr2");
SolrQuery query = new SolrQuery();
query.setQuery( "*:*" ); // get all
query.setFields("id"); // get the id field
query.setStart(0); // row to start on. First row is 0.
query.setRows(10); // number of rows to get at a time.
System.out.println(query.toString());
QueryResponse rsp = _solr.query( query );
List<BulkLoad1Data> bulkLoad1DataList = rsp.getBeans(BulkLoad1Data.class);
RplHelper1.rplSay("bulkLoad1DataList.size(): " + bulkLoad1DataList.size());
int count = 0;
Iterator<BulkLoad1Data> i = bulkLoad1DataList.iterator();
while (i.hasNext()) {
BulkLoad1Data bld = (BulkLoad1Data) i.next();
RplHelper1.rplSay("dumpSolr2 - count: " + ++count + " " +
" id: " + bld.getId());
}
}

does the mapper interface necessary

I am new in mybatis,and following mybatis3-user-guide.pdf.
I set up my first application.
However I found that I am not exactly know about the mapper interface.
By now,this is all the configuration for my application(take model User for example):
mybatis config.xml:
<configuration>
<typeAliases>
<typeAlias alias="User" type="com.king.mapper.User" />
</typeAliases>
<mappers>
<mapper resource="com/king/mapper/UserMapper.xml" />
</mappers>
</configuration>
UserMapper.xml:
<mapper namespace="com.king.mapper.UserMapper">
<select id="selectById" parameterType="int" resultMap="userMap">
select * from users where id = #{id}
</select>
<select id="selectAll" resultType="hashmap">
select * from users order by created_at desc
</select>
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into users (name,created_at,updated_at) values (#{name},current_timestamp,current_timestamp)
</insert>
<update id="update" parameterType="User">
update users set name = #{name},updated_at=current_timestamp where id = #{id}
</update>
<delete id="delete" parameterType="int">
delete from users where id = #{id}
</delete>
<resultMap id="userMap" type="User">
<result property="createDate" column="created_at" />
<result property="updateDate" column="updated_at" />
</resultMap>
</mapper>
Dao:
public abstract class AbstractSimpleDaoImpl<T> extends SqlSessionDaoSupport implements IDao<T> {
#Override
public T query(int id) {
return getSqlSession().selectOne(getMapperNamespace() + ".selectById", id);
}
#Override
public List<T> list() {
return getSqlSession().selectList(getMapperNamespace() + ".selectAll");
}
#Override
public int add(T entity) {
return getSqlSession().insert(getMapperNamespace() + ".insert", entity);
}
#Override
public int update(T entity) {
return getSqlSession().update(getMapperNamespace() + ".update", entity);
}
#Override
public void delete(T entity) {
getSqlSession().delete(getMapperNamespace() + ".delete", entity);
}
protected abstract String getMapperNamespace();
}
UserDao:
public class UserDao extends AbstractSimpleDaoImpl<User> {
private static String pack = "com.king.mapper.UserMapper";
#Override
protected String getMapperNamespace() {
return pack;
}
}
It worked. However I found that my example of mybatis will refer to the mapper interface.
It seems that I have to create a Interface named UserMapper in my above example.
But I wonder if it is necessary? and when I have to use it?
BTW,in my opinion,I found that what the mapper interface do just like the what the dao does. Since the dao and the interface may have so many methods with the same name.
You can create mapper interface UserMapper and avoid calling methods getSqlSession()... on your Dao object. So with mapper interface your xml configuration stay same but you can avoid Dao object at all. Just define interface like this:
public interface UserMapper {
public List<User> selectAll();
public User selectById(#Param("id") int id);
// rest is ommited
}
Names of methods must match with id of select/update/insert/detele in mapper file.
That's it.

How to call another method in the pojo class setter method [session file uploading application] of Hibernate and struts 2

Hi Friends i am developing an web application which uses hibernate and struts2. i am creating photo album i successfully done that with out using hibernate but, with hibernate it is having problem while inserting to the database. the module works like this as soon as the file uploaded it will insert the FileName, Contenttype,id and it suppose to insert the Image File(byte[]) Content also but it is showing Null in table value.. my code goes like this...
#Entity
#Table(name="PHOTOALBUM")
public class User implements Serializable {
#Id
#GeneratedValue
#Column(name="PHOTO_ID")
private Long id;
#Column(name="IMAGE")
private byte[] Image;
#Column(name="CONTENT_TYPE")
private String userImageContentType;
#Column(name="PHOTO_NAME")
private String userImageFileName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserImageFileName() {
return userImageFileName;
}
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public byte[] getImage() {
return Image;
}
public void setImage(byte[] Image) {
Image=Change(this.getUserImage());
this.Image = Image;
}
#Transient
private File userImage;
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public byte[] Change(File userImage)
{
// userImage=this.getUserImage();
// String name=userImage.getName();
// long len=userImage.length();
byte[] bFile = new byte[(int) userImage.length()];
try {
FileInputStream fileInputStream = new FileInputStream(userImage);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// System.out.println("The Name Of File In Pojo Class Is:="+ name);
//System.out.println("The Length Of File In Pojo Class Is:="+ len);
//System.out.println("The Content Of File In Pojo Class Is:="+ bFile);
return bFile;
}
}
and i am saving the values like this
public class UserDAOImpl implements UserDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a user.
*/
#Override
public void saveOrUpdateUser(User user) {
try {
session.saveOrUpdate(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a user.
*/
#Override
public void deleteUser(Long userId) {
try {
User user = (User) session.get(User.class, userId);
session.delete(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the users.
*/
#SuppressWarnings("unchecked")
#Override
public List<User> listUser() {
List<User> courses = null;
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single user by Id.
*/
#Override
public User listUserById(Long userId) {
User user = null;
try {
user = (User) session.get(User.class, userId);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
the struts action mapping goes like this...
\<package name="default" extends="hibernate-default">
<action name="saveOrUpdateUser"method="saveOrUpdate"class="com.srikanth.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list" class="com.srikanth.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="editUser" method="edit" class="com.srikanth.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="deleteUser" method="delete" class="com.srikanth.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
</package>
and my jsp goes like this
\<s:form action="saveOrUpdateUser">
<s:push value="user">
<s:hidden name="id" />
<s:file name="userImage" label="User Image" />
<s:submit />
</s:push>
</s:form>
<s:iterator value="userList" status="userStatus">
<s:property value="id" />
<s:property value="userImageFileName" />
<s:property value="userImageContentType" />
<img src='<s:property value="userImage" />' alt"" />
<s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a>
</s:iterator>
I am trying to call the Change Method so that it convert the file to byte[] and stored it in byte[] Image variable using setter but it is not working....
So please help me with this one .....
thanks in advance
As per my understand of question the problem is only inserting file into table. Copy & paste the Change() method into com.srikanth.web.UserAction class as you are using this action for every DB transaction. use Change() method before going to insert/update in DB.
For example:
public class UserAction extends ActionSupport{
//variable to get file from jsp
private File uploadedImage;
.....
//setters & getters for uploadedImage
#Override
public String gsexecute() throws Exception {
User user = new User();
//set image value as byteArray
user.setImage(Change(uploadedImage));
//insert or update DB here
return SUCCESS;
}
public byte[] Change(File userImage)
{
// userImage=this.getUserImage();
// String name=userImage.getName();
// long len=userImage.length();
byte[] bFile = new byte[(int) userImage.length()];
try {
FileInputStream fileInputStream = new FileInputStream(userImage);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// System.out.println("The Name Of File In Pojo Class Is:="+ name);
//System.out.println("The Length Of File In Pojo Class Is:="+ len);
//System.out.println("The Content Of File In Pojo Class Is:="+ bFile);
return bFile;
}
}
And make sure that the table column should support the byte array insert. Ex: use BLOB column type for MYSQL.

How can I bind to a helper property in Silverlight

For the sake of argument, here's a simple person class
public class Person : DependencyObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public static readonly DependencyProperty FirstNameProperty =
DependencyProperty.Register( "FirstName",
typeof ( string ),
typeof ( Person ),
null );
public static readonly DependencyProperty LastNameProperty =
DependencyProperty.Register( "LastName",
typeof( string ),
typeof( Person ),
null );
public string FirstName
{
get
{
return ( string ) GetValue( FirstNameProperty );
}
set
{
SetValue( FirstNameProperty, value );
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs( "FirstName" ));
}
}
public string LastName
{
get
{
return ( string ) GetValue( LastNameProperty );
}
set
{
SetValue( LastNameProperty, value );
if ( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) );
}
}
}
I want to go about creating a readonly property like this
public string FullName
{
get { return FirstName + " " + LastName; }
}
How does binding work in this scenario? I've tried adding a DependancyProperty and raised the PropertyChanged event for the fullname. Basically I just want to have a property that I can bind to that returns the fullname of a user whenever the first or last name changes. Here's the final class I'm using with the modifications.
public class Person : DependencyObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public static readonly DependencyProperty FirstNameProperty =
DependencyProperty.Register( "FirstName",
typeof ( string ),
typeof ( Person ),
null );
public static readonly DependencyProperty LastNameProperty =
DependencyProperty.Register( "LastName",
typeof( string ),
typeof( Person ),
null );
public static readonly DependencyProperty FullNameProperty =
DependencyProperty.Register( "FullName",
typeof( string ),
typeof( Person ),
null );
public string FirstName
{
get
{
return ( string ) GetValue( FirstNameProperty );
}
set
{
SetValue( FirstNameProperty, value );
if ( PropertyChanged != null )
{
PropertyChanged( this, new PropertyChangedEventArgs( "FirstName" ) );
PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) );
}
}
}
public string LastName
{
get
{
return ( string ) GetValue( LastNameProperty );
}
set
{
SetValue( LastNameProperty, value );
if ( PropertyChanged != null )
{
PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) );
PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) );
}
}
}
public string FullName
{
get { return GetValue( FirstNameProperty ) + " " + GetValue( LastNameProperty ); }
}
}
I'm not sure what you are trying to achieve here, but why is your Person class inheriting from DependencyObject and why are FirstName and LastName DependencyProperties? If all you want to do is bind the Person properties to user controls on your view, having the Person class implementing INotifyPropertyChanged is enough to make the data binding work. You will typically bind it to properties of a user control that are dependency properties (eg the Text property of a TextBlock).
Try this for you Person class:
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (value != _firstName)
{
_firstName = value;
RaisePropertyChanged("FirstName");
RaisePropertyChanged("FullName");
}
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
if (value != _lastName)
{
_lastName = value;
RaisePropertyChanged("LastName");
RaisePropertyChanged("FullName");
}
}
}
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
And use it like this in your view:
<Grid x:Name="LayoutRoot" Background="White" >
<TextBlock Text="{Binding FullName}"/>
</Grid>
Then, in your codebehind, you could instantiate it like so:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
DataContext = new Person { FirstName = "John", LastName = "Doe" };
}
}
HTH,
Phil
First of all your implementation of the existing FirstName and LastName properties is flawed. The DependencyObject already has ways to inform bindings of changes to the values and values can be changed by other mechanism than calling the Setter methods.
My first question would be why are FirstName and LastName dependency properties at all? That seems like a strange choice for this type of class. Phil's answer has already provided what I would really expect the correct answer to be.
However in case your code was actually a simplification and that there is in fact a genuine need to create dependency properties here is how it should be done:-
public class Person : DependencyObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public static readonly DependencyProperty FirstNameProperty =
DependencyProperty.Register( "FirstName",
typeof ( string ),
typeof ( Person ),
OnNamePropertyChanged);
public static readonly DependencyProperty LastNameProperty =
DependencyProperty.Register( "LastName",
typeof( string ),
typeof( Person ),
OnNamePropertyChanged);
private static void OnNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Person)d).OnNamePropertyChanged();
}
private void OnNamePropertyChanged()
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("FullName")));
}
public string FirstName
{
get { return GetValue(FirstNameProperty) as string; }
set { SetValue(FirstNameProperty, value); }
}
public string LastName
{
get { return GetValue(LastNameProperty) as string; }
set { SetValue(LastNameProperty, value); }
}
public string FullName
{
get { return FirstName + " " + LastName; }
}
}

Resources