I am trying to get list of Tbcompany table using Transformers.aliasToBean with 2 primary key fields.
I am using SQL SERVER and Hibernate 3.2.4.
My table has 2 primary fields.
Tbcompany.class
public class Tbcompany {
private TbcompanyId id;
private String hcompanycode;
public TbcompanyId getId() {
return id;
}
public void setId(TbcompanyId id) {
this.id = id;
}
public String getHcompanycode() {
return hcompanycode;
}
public void setHcompanycode(String hcompanycode) {
this.hcompanycode = hcompanycode;
}
}
And inside TbcompanyId.class :
public class TbcompanyId
implements Serializable
{
private String companycode;
private String companyname;
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TbcompanyId)) {
return false;
}
TbcompanyId other = ((TbcompanyId) o);
if (this.companycode == null) {
if (other.companycode!= null) {
return false;
}
} else {
if (!this.companycode.equals(other.companycode)) {
return false;
}
}
if (this.companyname == null) {
if (other.companyname!= null) {
return false;
}
} else {
if (!this.companyname.equals(other.companyname)) {
return false;
}
}
return true;
}
public int hashCode() {
int rtn = 17;
rtn = (rtn* 37);
if (this.companycode!= null) {
rtn = (rtn + this.companycode.hashCode());
}
rtn = (rtn* 37);
if (this.companyname!= null) {
rtn = (rtn + this.companyname.hashCode());
}
return rtn;
}
public String getCompanycode() {
return companycode;
}
public void setCompanycode(String companycode) {
this.companycode = companycode;
}
public String getCompanyname() {
return companyname;
}
public void setCompanyname(String companyname) {
this.companyname = companyname;
}
I want to create a form and use Transformers.aliasToBean to populate the form .
This query :
Query q;
q = session.createQuery("SELECT a.id.companycode as companycode,a.id.companyname as companyname,a.hcompanycode as hcompanycode FROM Tbcompany a");
q.setResultTransformer(Transformers.aliasToBean(Tbcompany.class));
list = q.list();
gives me an error of :
org.hibernate.PropertyNotFoundException: Could not find setter for companycode on class com.loansdb.data.Tbcompany
While this query :
Query q;
q = session.createQuery("SELECT a.id.companycode,a.id.companyname,a.hcompanycode as hcompanycode FROM
Tbcompany a");
q.setResultTransformer(Transformers.aliasToBean(Tbcompany.class));
list = q.list();
gives me this error :
org.hibernate.PropertyNotFoundException: Could not find setter for 0 on class com.loansdb.data.Tbcompany
Does anyone know how to do this?
The aliasToBean transformer use the name of the SQL columns returned and try to find a field with the same name on the class target that have a set method created.
So, your query returns a a.id.companycode:
SELECT a.id.companycode as companycode,a.id.companyname as companyname,a.hcompanycode as hcompanycode FROM Tbcompany a
The error said:
org.hibernate.PropertyNotFoundException: Could not find setter for companycode on class com.loansdb.data.Tbcompany
And your Tbcompany class does not have a setter to companycode.
So, to correct your Tbcompany class and looking your query, seems to me that the class it's something like:
public class Tbcompany {
private String companycode;
private String companycode;
private String companyname;
public String setCompanycode(String companycode) {
this.companycode = companycode;
}
// create the constructor, getters and setters
}
Related
I am using a #BeanParam like this:
#GET
public Response listAllPaged(#BeanParam PagedRequest pagedRequest) {
// Do stuff...
}
The bean itself:
public class PagedRequest {
#QueryParam("sortOrder")
#DefaultValue("0")
public int sortOrder;
}
Now I would like to change the type of sortOrder to the following enum:
public enum SortOrder {
ASC("asc"),
DESC("desc");
public final String sortOrder;
SortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
}
But as soon as I do this:
public class PagedRequest {
#QueryParam("sortOrder")
#DefaultValue("asc")
public SortOrder sortOrder;
}
My REST Endpoint cannot match the signature anymore and returns a 404. Why is that? I thought that the presence of a constructor accepting a single String should allow JAX-RS to do the conversion.
What am I doing wrong?
UPDATE
I managed to make it work like this, but it does not really answer my initial question...
public enum SortOrder {
ASC,
DESC;
public static SortOrder fromString(String param) {
String toUpper = param.toUpperCase();
try {
return valueOf(toUpper);
} catch (Exception e) {
return null;
}
}
}
The Enum.valueOf(String) method is used to resolve the value. Since your SorterOrder enums are uppercase you'd be required to send the parameter in uppercase.
If you want to pass the value in lowercase only you could change the enum names to lower case, e.g. SortOrder.asc.
If you don't know or don't want to care about the case the parameter is sent in you could use a ParamConverter.
public class SortOrderParamConverter implements ParamConverter<SortOrder> {
#Override
public SortOrder fromString(final String value) {
if (value != null) {
return SortOrder.valueOf(value.toUpperCase(Locale.ROOT));
}
return SortOrder.ASC;
}
#Override
public String toString(final SortOrder value) {
return value.name();
}
}
If you want a more generic approach you could create a ParamConverter or all enums.
#Provider
public class EnumParamConverterProvider implements ParamConverterProvider {
#Override
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType,
final Annotation[] annotations) {
if (!rawType.isEnum()) {
return null;
}
final Enum<?>[] constants = (Enum<?>[]) rawType.getEnumConstants();
return new ParamConverter<T>() {
#Override
#SuppressWarnings("unchecked")
public T fromString(final String value) {
if (value == null || value.isEmpty()) {
return null;
}
for (Enum<?> e : constants) {
if (e.name().equalsIgnoreCase(value)) {
return (T) e;
}
}
// No match, check toString()
for (Enum<?> e : constants) {
if (e.toString().equalsIgnoreCase(value)) {
return (T) e;
}
}
return null;
}
#Override
public String toString(final T value) {
return value != null ? value.toString() : null;
}
};
}
}
No errors on the apex class screen. An unexpected error occurs when you press the search button.
I got an error when I added the pagination code in the second half.
There was no problem before that.
Why?
public with sharing class AccountListCon {
static List<String> TARGET_FIELDS = new List<String>{
'Name'
};
public SearchCondition condition{ get;set; }
public List<AccountList__c> results { get;set; }
public String sortingField { get;set; }
public void init(){
this.condition = new SearchCondition();
this.results = new List<AccountList__c>();
}
public PageReference clear(){
init();
return null;
}
public PageReference search() {
if( condition.validate() ){
return null;
}
String soqlQuery = condition.getSoqlQuery();
System.debug('[soql] ' + soqlQuery);
try{
this.results = database.query(soqlQuery);
System.debug(this.results);
}catch(DmlException e){
ApexPages.addMessages(e);
System.debug('[DmlException]' + e);
}catch(Exception e){
ApexPages.addMessages(e);
System.debug('[Exception]' + e);
}
return null;
}
public PageReference sort(){
if(this.sortingField == null ){
return null;
}
if(this.sortingField == this.condition.sortkey){
this.condition.setOrderReverse();
}
else {
this.condition.sortkey = this.sortingField;
}
search();
return null;
}
public Class SearchCondition {
private Time JST_AM0 = Time.newInstance(9, 0, 0, 0);
public AccountList__c obj {get;set;}
public SearchCondition() {
this.obj = new AccountList__c();
sortkey = 'LastModifiedDate';
order = 'DESC';
}
public String getSoqlQuery(){
List<String> param = new String[]{ getFieldList(), getWhere(), getOrder() };
return String.format('SELECT {0} FROM AccountList__c {1} {2} LIMIT 500', param);
}
private String getFieldList(){
return String.join(TARGET_FIELDS, ',');
}
private String getWhere(){
List<String> param = new String[]{ };
--Omission--
if(param.isEmpty()){
return '';
}
return 'WHERE ' + String.join(param, ' AND ');
}
private String getOrder(){
List<String> param = new String[]{ sortkey, order };
return String.format('ORDER BY {0} {1}', param);
}
private DateTime adjustJSTtoGMS(DateTime day){
JST_AM0 = Time.newInstance(15, 0, 0, 0);
return Datetime.newInstance(day.date(), JST_AM0);
}
--Omission--
private static final Integer PAGE_SIZE = 10;
public Integer currentPage {get; set;}
public Integer totalPage {get; set;}
private ApexPages.StandardSetController ssController;
public Boolean getEnablePrev(){
return ssController.getHasPrevious();
}
public Boolean getEnableNext(){
return ssController.getHasNext();
}
public void PagingCtrl(){
}
public PageReference searchinit() {
ssController = new ApexPages.StandardSetController([SELECT Id, Name FROM Account]);
currentPage = ssController.getPageNumber();
ssController.setPageSize(PAGE_SIZE);
totalPage = (Integer)Math.ceil((Decimal)ssController.getResultSize() / PAGE_SIZE);
return null;
}
public void next() {
ssController.next();
currentPage = ssController.getPageNumber();
}
public void prev() {
ssController.previous();
currentPage = ssController.getPageNumber();
}
public List<Account> getAccountList(){
return (List<Account>)ssController.getRecords();
}
}
Attempt to de-reference a null object
FATAL_ERROR Class.AccountListCon.getEnablePrev: line 292, column 1
public Boolean getEnablePrev(){
return ssController.getHasPrevious();
}
It looks like getEnablePrev() is being called prior to searchInit(), where ssController is initialized. Your Visualforce page may be attempting to render the pagination area prior to completing the initialization of the required data; we couldn't tell the reason why without seeing the relevant portions of your Visualforce page.
In objectify, when I define a collection property with String datatype,
#IgnoreSave(IfEmpty.class)
private Set<String> collectionProperty = new HashSet<>();
and then look at a record in datastore, it appears indexed even though I have not annotated it with #Index.
Contrary, when I use a complex Object instead String, it does not appear as indexed.
Why are Collection properties indexed sometimes and sometimes not? And is there a way to determine this?
--
Unmodified code and screenshot from admin console/datastore:
#Entity
#Cache(expirationSeconds = 900)
public class Item extends StringId implements Serializable {
private static final Logger log = Logger.getLogger(Item.class.getSimpleName());
private static final long serialVersionUID = 1;
// Constructors
private Item() {}
#Nonnull
private static Item create(#Nonnull String itemId) {
Item item = (Item) new Item().setId(itemId);
item.piecesFromId();
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item create(#Nonnull String provider, #Nonnull String type, #Nonnull String identifier) {
String itemId = IdHelper.createItemId(provider, type, identifier);
Item item = ((Item) new Item().setId(itemId))
.setProvider(provider)
.setType(type)
.setIdentifier(identifier);
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item loadOrCreate(#Nonnull String itemId) {
Item item = ofy().load().type(Item.class).id(itemId).now();
if (item == null) {
item = Item.create(itemId);
}
return item;
}
#Nullable
public static Item load(#Nonnull String itemId) {
return ofy().load().type(Item.class).id(itemId).now();
}
#OnLoad
private void piecesFromId() {
provider = IdHelper.getProvider(id);
type = IdHelper.getType(id);
identifier = IdHelper.getIdentifier(id);
}
public Item save() {
ofy().defer().save().entity(this);
return this;
}
#OnSave
private void integrity() {
if (id == null) { throw new RuntimeException("Id must not be null."); }
if (itemPreview == null) { throw new RuntimeException("itemPreview must not be null."); }
if (provider == null || type == null || identifier == null) { throw new RuntimeException("provider, type and identifier must not be null."); }
if (!id.equals(IdHelper.createItemId(provider, type, identifier))) { throw new RuntimeException("id does not coincide with provider, type and identifier."); }
if (!id.equals(itemPreview.getItemId())) { throw new RuntimeException("id does not coincide with id in itemPreview."); }
}
#OnSave
private void timestamp() {
if (created == null) {
created = System.currentTimeMillis();
}
}
// Properties
#Ignore
private String provider;
#Ignore
private String type;
#Ignore
private String identifier;
#Ignore // json
private ItemPreview itemPreview;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> subscribedUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> notifyUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> blacklistingUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private Long created;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfDefault.class)
#Index
private Status status = Status.ACTIVE;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String suspensionNotice;
// Json
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String itemPreviewJson;
private static Type itemPreviewType = new TypeToken<ItemPreview>(){}.getType();
#OnLoad
private void itemPreviewFromJson() {
if (itemPreviewJson != null) {
itemPreview = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.fromJson(itemPreviewJson, itemPreviewType);
}
}
#OnSave
private void itemPreviewToJson() {
itemPreviewJson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.toJson(itemPreview, itemPreviewType);
}
// Accessors
public String getProvider() {
return provider;
}
public Item setProvider(String provider) {
this.provider = provider;
return this;
}
public String getType() {
return type;
}
public Item setType(String type) {
this.type = type;
return this;
}
public String getIdentifier() {
return identifier;
}
public Item setIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public ItemPreview getItemPreview() {
return itemPreview;
}
public Item setItemPreview(ItemPreview itemPreview) {
this.itemPreview = itemPreview;
return this;
}
public Set<String> getSubscribedUserIds() {
return subscribedUserIds;
}
public Item setSubscribedUserIds(Set<String> subscribedUserIds) {
this.subscribedUserIds = subscribedUserIds;
return this;
}
public Set<String> getNotifyUserIds() {
return notifyUserIds;
}
public Item setNotifyUserIds(Set<String> notifyUserIds) {
this.notifyUserIds = notifyUserIds;
return this;
}
public Set<String> getBlacklistingUserIds() {
return blacklistingUserIds;
}
public Item setBlacklistingUserIds(Set<String> blacklistingUserIds) {
this.blacklistingUserIds = blacklistingUserIds;
return this;
}
public Long getCreated() {
return created;
}
public Item setCreated(Long created) {
this.created = created;
return this;
}
public Status getStatus() {
return status;
}
public Item setStatus(Status status) {
this.status = status;
return this;
}
public String getSuspensionNotice() {
return suspensionNotice;
}
public Item setSuspensionNotice(String suspensionNotice) {
this.suspensionNotice = suspensionNotice;
return this;
}
// Collections
public static Map<String, Item> loadAll(Set<String> itemIds) {
return ofy().load().type(Item.class).ids(itemIds);
}
}
I have a parent and a child class. When I run the app I'm getting following error:
Error in meta-data for com.twitterjaya.model.HistoryDeviceJPA: More than one primary key field.
I have no idea why it says I defined more than one primary key. Any suggestion would be appreciated.
#Entity(name = "HistoryJPA")
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#DiscriminatorValue("HistoryJPA")
public class HistoryJPA {
#Id
String pageAddress;
String domain;
String pageTitle;
long pageVisits;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HistoryJPA that = (HistoryJPA) o;
if (!pageAddress.equals(that.pageAddress)) return false;
return true;
}
#Override
public int hashCode() {
return pageAddress.hashCode();
}
#Override
public String toString() {
return "HistoryJPA{" +
"pageAddress='" + pageAddress + '\'' +
", domain='" + domain + '\'' +
", pageTitle='" + pageTitle + '\'' +
", pageVisits=" + pageVisits +
'}';
}
public String getPageAddress() {
return pageAddress;
}
public void setPageAddress(String pageAddress) {
this.pageAddress = pageAddress;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
public long getPageVisits() {
return pageVisits;
}
public void setPageVisits(long pageVisits) {
this.pageVisits = pageVisits;
}
}
and child class:
#Entity(name = "HistoryDeviceJPA")
#DiscriminatorValue("HistoryDeviceJPA")
public class HistoryDeviceJPA extends HistoryJPA {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userUUID;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
HistoryDeviceJPA that = (HistoryDeviceJPA) o;
if (!id.equals(that.id)) return false;
if (!userUUID.equals(that.userUUID)) return false;
return true;
}
#Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + id.hashCode();
result = 31 * result + userUUID.hashCode();
return result;
}
#Override
public String toString() {
return "HistoryDeviceJPA{" +
"id=" + id +
", userUUID='" + userUUID + '\'' +
'}';
}
public String getUserUUID() {
return userUUID;
}
public void setUserUUID(String userUUID) {
this.userUUID = userUUID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
As explained by the error message, you have two primary keys (annotated with #Id):
one in HistoryJPA on field pageAddress
one in HistoryDeviceJPA on field id
You should get rid of one of them, or create a composite primary key depending on your needs.
Getting error preverifying class java/langnoclassdeffounderror : java/lang/comparable for java me platform.
I have migrated my J2SE code to J2ME code. I am aware that some functions J2SE functions don't work on J2ME platform. Therefore, i have already crosschecked for the Comparable class. It is included in Java ME libraries.
Now, i am unable to resolve the errors. Please help me out here.
Please refer the code below:
import java.io.Serializable;
import aiproject.CompareToBuilder;
import aiproject.EqualsBuilder;
import aiproject.HashCodeBuilder;
import aiproject.ToStringBuilder;
public class WordProbability implements Comparable, Serializable {
private static final int UNDEFINED = -1;
private String word = "";
private String category = ICategorisedCategorizer.DEFAULT_CATEGORY;
private long matchingCount = UNDEFINED;
private long nonMatchingCount = UNDEFINED;
private double probability = ICategorizer.NEUTRAL_PROBABILITY;
public WordProbability() {
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String w) {
setWord(w);
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String c, String w) {
setCategory(c);
setWord(w);
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String w, double probability) {
setWord(w);
setProbability(probability);
}
public WordProbability(String w, long matchingCount, long nonMatchingCount) {
setWord(w);
setMatchingCount(matchingCount);
setNonMatchingCount(nonMatchingCount);
}
public void setWord(String w) {
this.word = w;
}
public void setCategory(String category) {
this.category = category;
}
public void setProbability(double probability) {
this.probability = probability;
this.matchingCount = UNDEFINED;
this.nonMatchingCount = UNDEFINED;
}
public void setMatchingCount(long matchingCount) {
if (matchingCount < 0) {
throw new IllegalArgumentException("matchingCount must be greater than 0");
}
this.matchingCount = matchingCount;
calculateProbability();
}
public void setNonMatchingCount(long nonMatchingCount) {
if (nonMatchingCount < 0) {
throw new IllegalArgumentException("nonMatchingCount must be greater than 0");
}
this.nonMatchingCount = nonMatchingCount;
calculateProbability();
}
public void registerMatch() {
if (matchingCount == Long.MAX_VALUE) {
throw new UnsupportedOperationException("Long.MAX_VALUE reached, can't register more matches");
}
matchingCount++;
calculateProbability();
}
public void registerNonMatch() {
if (nonMatchingCount == Long.MAX_VALUE) {
throw new UnsupportedOperationException("Long.MAX_VALUE reached, can't register more matches");
}
nonMatchingCount++;
calculateProbability();
}
private void calculateProbability() {
String method = "calculateProbability() ";
double result = ICategorizer.NEUTRAL_PROBABILITY;
if (matchingCount == 0) {
if (nonMatchingCount == 0) {
result = ICategorizer.NEUTRAL_PROBABILITY;
} else {
result = ICategorizer.LOWER_BOUND;
}
} else {
result = BayesianCategorizer.normaliseSignificance((double) matchingCount / (double) (matchingCount + nonMatchingCount));
}
probability = result;
}
/**
* output
*/
public double getProbability() {
return probability;
}
public long getMatchingCount() {
if (matchingCount == UNDEFINED) {
throw new UnsupportedOperationException("MatchingCount has not been defined");
}
return matchingCount;
}
public long getNonMatchingCount() {
if (nonMatchingCount == UNDEFINED) {
throw new UnsupportedOperationException("nonMatchingCount has not been defined");
}
return nonMatchingCount;
}
public String getWord() {
return word;
}
public String getCategory() {
return category;
}
public boolean equals(Object o) {
if (!(o instanceof WordProbability)) {
return false;
}
WordProbability rhs = (WordProbability) o;
return new EqualsBuilder().append(getWord(), rhs.getWord()).append(getCategory(), rhs.getCategory()).isEquals();
}
public int compareTo(java.lang.Object o) {
if (!(o instanceof WordProbability)) {
throw new ClassCastException(o.getClass() + " is not a " + this.getClass());
}
WordProbability rhs = (WordProbability) o;
return new CompareToBuilder().append(this.getCategory(), rhs.getCategory()).append(this.getWord(), rhs.getWord()).toComparison();
}
public String toString() {
return new ToStringBuilder(this).append("word", word).append("category", category).append("probability", probability).append("matchingCount", matchingCount).append("nonMatchingCount", nonMatchingCount).toString();
}
public int hashCode() {
return new HashCodeBuilder(17, 37).append(word).append(category).toHashCode();
}
}
I don't see a Comparable in the javadocs of JavaME.
So I think it is not there.
Where did you found it?
Maybe some Lib or JSR has included it. Than you need to include this in the project settings.
If you just need the interface, you can define it yourself.