I using broadleaf-commerce famework for my program. I just want to know, how to visibility of AdminPresentationCollection in to config entity file. I config in js file but it doesn't work.
This's my entity. It use #AdminPresentation annotations and #AdminPresentationCollection annotations :
#Entity
#Table(name="BLC_PRICE_LIST")
#Inheritance(strategy = InheritanceType.JOINED)
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
#SQLDelete(sql="UPDATE BLC_PRICE_LIST SET ARCHIVED = 'Y' WHERE PRICE_LIST_ID = ?")
#DirectCopyTransform({
#DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.SANDBOX, skipOverlaps=true),
#DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_CATALOG)
})
public class PriceListImpl implements PriceList, PriceListAdminPresentation, AdminMainEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "PriceListId")
#GenericGenerator(
name="PriceListId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
#Parameter(name="segment_value", value="PriceListImpl"),
#Parameter(name="entity_name", value="com.community.core.pricelist.domain.PriceListImpl")
}
)
#Column(name = "CUSTOMER_RESTRICTION_RULE_TYPE")
#AdminPresentation(
friendlyName = "prices_rule_customer_title_group",
group = GroupName.Customer, order = FieldOrder.TargetCustomer,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration="com.community.core.pricelist.service.type.PriceListCustomerRestrictionRuleType",
defaultValue = "prices_rule_customer_available_for_all_customer",
tooltip = "prices_rule_customer_tooltip"
)
protected String customerRestrictionRuleType;
#OneToMany(mappedBy = "priceList",
targetEntity = PriceListPriceListRuleXrefImpl.class,
cascade = { CascadeType.ALL },
orphanRemoval = true)
#MapKey(name = "key")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blPriceLists")
#AdminPresentationMapFields(
toOneTargetProperty = "priceListRule",
toOneParentProperty = "priceList",
mapDisplayFields = {
#AdminPresentationMapField(
fieldName = RuleIdentifier.CUSTOMER_FIELD_KEY,
fieldPresentation = #AdminPresentation(
fieldType = SupportedFieldType.RULE_SIMPLE,
group = GroupName.Customer,
order = FieldOrder.CustomerRule,
ruleIdentifier = RuleIdentifier.CUSTOMER,
friendlyName = "RESTRICT TO THE FOLLOWING CUSTOMERS"
)
)
,
#AdminPresentationMapField(
fieldName = RuleIdentifier.PRICING_CONTEXT_FIELD_KEY,
fieldPresentation = #AdminPresentation(
fieldType = SupportedFieldType.RULE_SIMPLE,
group = GroupName.PricingContext,
order = FieldOrder.PricingContext,
ruleIdentifier = RuleIdentifier.PRICING_CONTEXT,
friendlyName = "price_list_rule_pricing_context_lab")
)
,
#AdminPresentationMapField(
fieldName = RuleIdentifier.REQUEST_FIELD_KEY,
fieldPresentation = #AdminPresentation(
fieldType = SupportedFieldType.RULE_SIMPLE,
group = GroupName.PricingContext,
order = 9000,
ruleIdentifier = RuleIdentifier.REQUEST,
friendlyName = "LIMIT TO CERTAIN WEB REQUESTS?")
)
}
)
Map<String, PriceListPriceListRuleXref> priceListMatchRules = new HashMap<String, PriceListPriceListRuleXref>();
#OneToMany(mappedBy = "priceList", targetEntity = PriceModifierImpl.class,
cascade = { CascadeType.ALL }, orphanRemoval = true)
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blPriceLists")
#BatchSize(size = 50)
#AdminPresentationCollection( friendlyName = "Price Modifiers",
group = GroupName.PricingContext,
order = 20000,
addType = AddMethodType.PERSIST
,showIfFieldEquals={
#org.broadleafcommerce.common.presentation.FieldValueConfiguration(
fieldName = "customerRestrictionRuleType",
fieldValues = {"ALL_CUSTOMERS", "A","B", "a" , "b"}
)
}
)
protected List<PriceModifier> priceModifier = new ArrayList<PriceModifier>(100);
#Column(name = "ERROR_CODE")
#AdminPresentation(friendlyName = "productOption_errorCode",
group = GroupName.PricingContext, order = 21000)
protected String errorCode;
#Override
public Boolean getIsPricingContext() {
return isPricingContext;
}
#Override
public void setIsPricingContext(Boolean isPricingContext) {
this.isPricingContext = isPricingContext;
}
#Override
public Boolean getIsRequest() {
return isRequest;
}
#Override
public void setIsRequest(Boolean isRequest) {
this.isRequest = isRequest;
}
#Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
public String getCustomerRestrictionRuleType() {
return customerRestrictionRuleType;
//return DynamicTranslationProvider.getValue(this, "customerRestrictionRuleType", customerRestrictionRuleType);
}
public void setCustomerRestrictionRuleType(String customerRestrictionRuleType) {
this.customerRestrictionRuleType = customerRestrictionRuleType;
}
#Override
public Map<String, PriceListPriceListRuleXref> getPriceListMatchRulesXref() {
return priceListMatchRules;
}
#Override
public void setPriceListMatchRulesXref(Map<String, PriceListPriceListRuleXref> priceListMatchRulesXref) {
this.priceListMatchRules = priceListMatchRulesXref;
}
#Override
public List<PriceModifier> getPriceModifier() {
return priceModifier;
}
#Override
public void setPriceModifier(List<PriceModifier> priceModifier) {
this.priceModifier = priceModifier;
}
#Override
public Character getArchived() {
ArchiveStatus temp;
if (archiveStatus == null) {
temp = new ArchiveStatus();
} else {
temp = archiveStatus;
}
return temp.getArchived();
}
#Override
public void setArchived(Character archived) {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
archiveStatus.setArchived(archived);
}
#Override
public boolean isActive() {
return DateUtil.isActive(startDate, endDate, true) && 'Y'!=getArchived();
}
#Override
public <G extends PriceList> CreateResponse<G> createOrRetrieveCopyInstance(MultiTenantCopyContext context) throws CloneNotSupportedException {
CreateResponse<G> createResponse = context.createOrRetrieveCopyInstance(this);
if (createResponse.isAlreadyPopulated()) {
return createResponse;
}
PriceList cloned = createResponse.getClone();
cloned.setName(name);
return createResponse;
}
#Override
public String getMainEntityName() {
return getName();
}
#Override
public PriceList createPriceList(){
return new PriceListImpl();
}
}
And this is my enum:
public static final PriceListCustomerRestrictionRuleType ALL_A = new PriceListCustomerRestrictionRuleType("ALL_CUSTOMERS", "AVAILABLE TO ALL CUSTOMERS");
public static final PriceListCustomerRestrictionRuleType A_RULE_ASSIGNMENT_A = new PriceListCustomerRestrictionRuleType("CUSTOMER_RULE_ASSIGNMENT_CUSTOMERS", "CUSTOMER RULE AND ASSIGNMENT TO CUSTOMERS");
And this is my js file:
(function($, BLCAdmin) {
$.each(['com.community.core.pricelist.domain.PriceList'], function(idx, clazz) {
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-customerRestrictionRuleType',
'#field-priceListMatchRules---CUSTOMER',
'CUSTOMER_RULE_ASSIGNMENT_CUSTOMERS'
);
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-isPricingContext',
'#field-priceListMatchRules---PRICING-CONTEXT',
'true'
);
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-isRequest',
'#field-priceListMatchRules---REQUEST',
'true'
);
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-customerRestrictionRuleType',
'#field-priceModifier',
'ALL_CUSTOMERS'
);
/*BLCAdmin.addDependentFieldHandler(
clazz,
'#field-customerRestrictionRuleType',
'#field-priceModifier',
'ALL_CUSTOMERS'
);*/
});
/*$.each(['com.community.core.pricelist.domain.PriceModifier'], function(idx, clazz) {
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-isTargetedItemsRule',
'#field-priceModifierMatchRules---PRODUCT',
'true'
);
});*/
})(jQuery, BLCAdmin);
Help me! Many thank!
Related
I try to use the pickList component of Primefaces. My converter does not work properly and I don't know why.
This is my ManagedBean:
#ManagedBean(name = "comMB")
#SessionScoped
public class TeamCompetitionBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<Team> teams;
List<Team> source;
List<Team> source1;
List<Team> target;
#ManagedProperty("#{team}")
private TeamServiceI teamService;
List<String> teamNameList ;
// public TeamCompetitionBean() {
public DualListModel<Team> getTeams() {
// Players
teamNameList = new ArrayList<String>();
source = new ArrayList<Team>();
target = new ArrayList<Team>();
source.addAll(getTeamService().getTeam());
teams = new DualListModel<Team>(source, target);
return teams;
}
public void setTeams(DualListModel<Team> teams) {
this.teams = teams;
}
public void onTransfer(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((Team) item).getTeamName()).append("<br />");
}
FacesMessage msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Items Transferred");
msg.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public TeamServiceI getTeamService() {
return teamService;
}
public void setTeamService(TeamServiceI teamService) {
this.teamService = teamService;
}
public List<Team> getSource() {
return source;
}
public void setSource(List<Team> source) {
this.source = source;
}
public List<Team> getTarget() {
return target;
}
public void setTarget(List<Team> target) {
this.target = target;
}
public void afficher(){
System.out.println(target);
System.out.println(source);
}
}
and this is my entity class that I would like to load in my pickList:
#Entity
#Table(name = "team", catalog = "competition_manager")
public class Team implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idTeam;
private Stadium stadium;
private League league;
private String teamName;
// getters and setters
#Override
public String toString() {
return teamName.toString();
}
#Override
public boolean equals(Object obj) {
if (!(obj instanceof Team)) {
return false;
}
Team f = (Team) obj;
return (this.idTeam == f.getIdTeam());
}
Now, this is my custom Converter:
#FacesConverter(forClass = Team.class, value = "teamConverter")
public class TeamConverter implements Converter {
Team team;
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value) {
System.out.println("hello object");
if (value == null || value.length() == 0) {
return null;
}
ApplicationContext ctx = FacesContextUtils
.getWebApplicationContext(FacesContext.getCurrentInstance());
TeamBean controller = (TeamBean) ctx.getBean("teamMB");
List<Team> liststagiaire = controller.getTeamList();
for (int i = 0; i < liststagiaire.size(); i++)
{
team = liststagiaire.get(i);
if (team.getIdTeam() == getKey(value)) {
break;
}
}
return team;
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component,
Object object) {
System.out.println("hello string");
if (object == null) {
System.out.println("hello string null");
return null;
}
if (object instanceof Team) {
System.out.println("hello string intance of");
Team o = (Team) object;
String i = getStringKey(o.getIdTeam());
return i;
} else {
System.out.println("hello throw");
throw new IllegalArgumentException("object " + object
+ " is of type " + object.getClass().getName()
+ "; expected type: " + Team.class.getName());
}
}
}
And finally this is my XHTML page:
<p:pickList id="teamPickList" value="#{comMB.teams}" var="team"
itemValue="#{team}" itemLabel="#{team}" converter="teamConverter">
</p:pickList>
Your problem is comming from this line (in your class TeamConverter) :
if (team.getIdTeam() == getKey(value)) {
You can't compare Integer objects like that, because doing like this you are comparing reference. You should replace this line by
if (team.getIdTeam().intValue() == getKey(value).intValue()) {
You have the same problem in your class Team :
return (this.idTeam == f.getIdTeam());
should be replaced by :
return (this.idTeam.intValue() == f.getIdTeam().intValue());
Not related :
You don't need to use getKey and getStringKey, you could replace them simply like this :
getKey(value) // this
Integer.valueOf(value) // by this
and
getStringKey(o.getIdTeam()) // this
o.getIdTeam().toString() // by this
Also you should replace itemLabel="#{team}" by itemLabel="#{team.teamName}" in your view.
There are a couple of answers out there for this already, but I have not been able to find anything conclusive. This is the jist of what I am trying to do:
EquityInstrument
public class EquityInstrument : INotifyPropertyChanged
{
private string _Symbol;
public string Symbol
{
get
{
return _Symbol;
}
set
{
_Symbol = value;
OnPropertyChanged("Symbol");
}
}
public EquityInstrument(string Symbol)
{
this.Symbol = Symbol;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string FieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(FieldName);
}
}
}
OptionInstrument
public class OptionInstrument : INotifyPropertyChanged;
{
public readonly EquityInstrument UnderlyingInstrument;
private double _StrikePrice;
public double StrikePrice
{
get
{
return _StrikePrice;
}
set
{
_StrikePrice = value;
OnPropertyChanged("StrikePrice");
}
}
private DateTime _Expiration;
public DateTime Expiration;
{
get
{
return _Expiration;
}
set
{
_Expiration = value;
OnPropertyChanged("Expiration");
}
}
public OptionInstrument(string Symbol, double StrikePrice, DateTime Expiration)
{
this.Symbol = Symbol;
this.StrikePrice = StrikePrice;
this.Expiration = Expiration;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string FieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(FieldName);
}
}
}
This code initiates the Option Table...
GridControl OptionGrid = new GridControl();
BindingList<OptionInstrument> BoundList = new BindingList<OptionInstrument>();
public void InitializeDataTable()
{
OptionGrid.DataSource = new BindingSource() { DataSource = BoundList };
BandedGridColumn Column0 = new BandedGridColumn();
Column0.FieldName = "Symbol";
BandedGridColumn Column1 = new BandedGridColumn();
Column1.FieldName = "StrikePrice";
BandedGridColumn Column2 = new BandedGridColumn();
Column2.FieldName = "Expiration";
BandedGridView MainView = (BandedGridView)OptionGrid.MainView;
MainView.Columns.Add(Column0);
MainView.Columns.Add(Column1);
MainView.Columns.Add(Column2);
BoundList.Add(new OptionInstrument("DELL", 12.22, new DateTime(2012, 10, 12));
BoundList.Add(new OptionInstrument("MSFT", 13.23, new DateTime(2012, 09, 16));
BoundList.Add(new OptionInstrument("SPY", 12.23, new DateTime(2012, 07, 18));
}
What do you think? Are there any good design patterns to accomplish this?
My web application is a CRUD web application based on JSF 2.0 / JPA using Java EE 5 and JDK 1.6. Running on Glassfish 3.1. The IDE is Netbeans 7.0. (I do not use EJB, nor CDI).
THE PROBLEM
What I can achieve now is perform CRUD on my entities. Which is fine. For each entity I have:
List.xhtml (LIsting all Datamodel items for that entity in datatable)
Create.xhtml (A form to create a new item)
View.xhtml (a form to view an item)
Edit.xhtml (a form to edit an item)
Structure
entities package: entities.
jpa.controllers package: JPA controllers (Javax persistence..).
jsf package: a managed bean for each entity (session Scoped).
But the main problem is parent-leaf navigation. I want my webapp to do the same thing as the Demo application Agile ScrumToys that comes along shipped with Netbeans 7.0. or the demo webapp from SpringFuse, otherwise :
E.G: When you display a list of WRITERS in a you have the last <h:column> where you put three <h:commandLink /> for editing, viewing and deleting the selected row.
What I intend to do is to add another in the same column that allows me to view a collection of child objects related to that selected row.
Hence, I want to show the list of BOOKS written by a given WRITER.
WRITER 1 ---------- * BOOK (one-to-many) relationship.
When the user clicks on the
<h:commandButton action="#{someManagedBean.showBooksForWriter}" value="#{i18n.listBooks}" /> it forwards him to the /book/List.xhtml (list of the selected WRITEr row should appear). And so on, from the book datatable, from a given row, I click on <h:commandLink action="#{someManagedBean.showReferencesForBook}" value="List of Book References"/> to get the list of references for the given book.
A given hint by #Matt was to use a method in the book managed bean:
public showBooksForWriter(Writer writer) {
// TODO: get the selected writer
// Get the list of books for the selected writer
return "/book/List"; // Outcome
}
And in the view :
<h:datatable value="#{writerController.items}" var="w">
.....
<h:column>
<h:commandButton action="#{bookController.showBooksForWriter(w}" value="Show Books For Writer"/>
</h:column>
....
</h:datatable>
But I could not figure how to (DataModel is driving mad). So if anyone could help! It would be very appreciated!
Below is my code
the WRITER entity:
package entities;
import javax.persistence.*; // other imports
#Entity
#Table(name = "WRITER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Writer.findAll", query = "SELECT w FROM Writer w"),
#NamedQuery(name = "Writer.findByWriterid", query = "SELECT w FROM Writer w WHERE w.writerid = :writerid"),
#NamedQuery(name = "Writer.findByName", query = "SELECT w FROM Writer w WHERE w.name = :name"),
#NamedQuery(name = "Writer.findBySurname", query = "SELECT w FROM Writer w WHERE w.surname = :surname"),
#NamedQuery(name = "Writer.findByMiddlename", query = "SELECT w FROM Writer w WHERE w.middlename = :middlename"),
#NamedQuery(name = "Writer.findByIsRewarded", query = "SELECT w FROM Writer w WHERE w.isRewarded = :isRewarded")})
public class Writer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "writerid")
private Integer writerid;
#Size(max = 45)
#Column(name = "name")
private String name;
#Size(max = 45)
#Column(name = "surname")
private String surname;
#Size(max = 45)
#Column(name = "middlename")
private String middlename;
#Column(name = "isRewarded")
private Boolean isRewarded;
#ManyToMany(mappedBy = "writerList")
private List<Topic> topicList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private List<Evaluation> evaluationList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private List<Book> bookList;
public Writer() {
}
public Writer(Integer writerid) {
this.writerid = writerid;
}
public Integer getWriterid() {
return writerid;
}
public void setWriterid(Integer writerid) {
this.writerid = writerid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public Boolean getIsRewarded() {
return isRewarded;
}
public void setIsRewarded(Boolean isRewarded) {
this.isRewarded = isRewarded;
}
#XmlTransient
public List<Topic> getTopicList() {
return topicList;
}
public void setTopicList(List<Topic> topicList) {
this.topicList = topicList;
}
#XmlTransient
public List<Evaluation> getEvaluationList() {
return evaluationList;
}
public void setEvaluationList(List<Evaluation> evaluationList) {
this.evaluationList = evaluationList;
}
#XmlTransient
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (writerid != null ? writerid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Writer)) {
return false;
}
Writer other = (Writer) object;
if ((this.writerid == null && other.writerid != null) || (this.writerid != null && !this.writerid.equals(other.writerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return getMiddlename();
}
}
The Writer MANAGED BEAN
package jsf;
import entities.Writer;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jpa.controllers.WriterJpaController;
import javax.faces.bean.ManagedBean;
// other imports here
#ManagedBean(name = "writerController")
#SessionScoped
public class WriterController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "writerPU")
private EntityManagerFactory emf = null;
private Writer current;
private DataModel items = null;
private WriterJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public WriterController() {
}
public Writer getSelected() {
if (current == null) {
current = new Writer();
selectedItemIndex = -1;
}
return current;
}
private WriterJpaController getJpaController() {
if (jpaController == null) {
jpaController = new WriterJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getWriterCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findWriterEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Writer();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getWriterid());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getWriterCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findWriterEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findWriterEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findWriterEntities(), true);
}
#FacesConverter(forClass = Writer.class)
public static class WriterControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
WriterController controller = (WriterController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "writerController");
return controller.getJpaController().findWriter(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Writer) {
Writer o = (Writer) object;
return getStringKey(o.getWriterid());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + WriterController.class.getName());
}
}
}
}
JSF Utility Class
package jsf.util;
import javax.faces.application.FacesMessage;
// Other imports here
public class JsfUtil {
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
public static void addErrorMessage(Exception ex, String defaultMsg) {
String msg = ex.getLocalizedMessage();
if (msg != null && msg.length() > 0) {
addErrorMessage(msg);
} else {
addErrorMessage(defaultMsg);
}
}
public static void addErrorMessages(List<String> messages) {
for (String message : messages) {
addErrorMessage(message);
}
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public static void addSuccessMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
}
public static String getRequestParameter(String key) {
return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
}
public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) {
String theId = JsfUtil.getRequestParameter(requestParameterName);
return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId);
}
}
JSF Pagination helper
package jsf.util;
import javax.faces.model.DataModel;
public abstract class PaginationHelper {
private int pageSize;
private int page;
public PaginationHelper(int pageSize) {
this.pageSize = pageSize;
}
public abstract int getItemsCount();
public abstract DataModel createPageDataModel();
public int getPageFirstItem() {
return page * pageSize;
}
public int getPageLastItem() {
int i = getPageFirstItem() + pageSize - 1;
int count = getItemsCount() - 1;
if (i > count) {
i = count;
}
if (i < 0) {
i = 0;
}
return i;
}
public boolean isHasNextPage() {
return (page + 1) * pageSize + 1 <= getItemsCount();
}
public void nextPage() {
if (isHasNextPage()) {
page++;
}
}
public boolean isHasPreviousPage() {
return page > 0;
}
public void previousPage() {
if (isHasPreviousPage()) {
page--;
}
}
public int getPageSize() {
return pageSize;
}
} // END of CLASS
The JPA Controller
package jpa.controllers;
import entities.Writer;
// other imports here
public class WriterJpaController implements Serializable {
public WriterJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Writer writer) throws RollbackFailureException, Exception {
if (writer.getTopicList() == null) {
writer.setTopicList(new ArrayList<Topic>());
}
if (writer.getEvaluationList() == null) {
writer.setEvaluationList(new ArrayList<Evaluation>());
}
if (writer.getBookList() == null) {
writer.setBookList(new ArrayList<Book>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Topic> attachedTopicList = new ArrayList<Topic>();
for (Topic topicListTopicToAttach : writer.getTopicList()) {
topicListTopicToAttach = em.getReference(topicListTopicToAttach.getClass(), topicListTopicToAttach.getTopicname());
attachedTopicList.add(topicListTopicToAttach);
}
writer.setTopicList(attachedTopicList);
List<Evaluation> attachedEvaluationList = new ArrayList<Evaluation>();
for (Evaluation evaluationListEvaluationToAttach : writer.getEvaluationList()) {
evaluationListEvaluationToAttach = em.getReference(evaluationListEvaluationToAttach.getClass(), evaluationListEvaluationToAttach.getEvaluationPK());
attachedEvaluationList.add(evaluationListEvaluationToAttach);
}
writer.setEvaluationList(attachedEvaluationList);
List<Book> attachedBookList = new ArrayList<Book>();
for (Book bookListBookToAttach : writer.getBookList()) {
bookListBookToAttach = em.getReference(bookListBookToAttach.getClass(), bookListBookToAttach.getBookPK());
attachedBookList.add(bookListBookToAttach);
}
writer.setBookList(attachedBookList);
em.persist(writer);
for (Topic topicListTopic : writer.getTopicList()) {
topicListTopic.getWriterList().add(writer);
topicListTopic = em.merge(topicListTopic);
}
for (Evaluation evaluationListEvaluation : writer.getEvaluationList()) {
Writer oldWriterOfEvaluationListEvaluation = evaluationListEvaluation.getWriter();
evaluationListEvaluation.setWriter(writer);
evaluationListEvaluation = em.merge(evaluationListEvaluation);
if (oldWriterOfEvaluationListEvaluation != null) {
oldWriterOfEvaluationListEvaluation.getEvaluationList().remove(evaluationListEvaluation);
oldWriterOfEvaluationListEvaluation = em.merge(oldWriterOfEvaluationListEvaluation);
}
}
for (Book bookListBook : writer.getBookList()) {
Writer oldWriterOfBookListBook = bookListBook.getWriter();
bookListBook.setWriter(writer);
bookListBook = em.merge(bookListBook);
if (oldWriterOfBookListBook != null) {
oldWriterOfBookListBook.getBookList().remove(bookListBook);
oldWriterOfBookListBook = em.merge(oldWriterOfBookListBook);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Writer writer) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
// remainder of code goes here
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
// remainder of code goes here
}
public List<Writer> findWriterEntities() {
return findWriterEntities(true, -1, -1);
}
public List<Writer> findWriterEntities(int maxResults, int firstResult) {
return findWriterEntities(false, maxResults, firstResult);
}
private List<Writer> findWriterEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Writer.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Writer findWriter(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Writer.class, id);
} finally {
em.close();
}
}
public int getWriterCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Writer> rt = cq.from(Writer.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Hi All
i wonder how to select between many to one relational
i have two table Sub_category and Items
sub category is own of relational, it contain list of Items
Two class follow:
#Entity
#Table(name = "item")
#NamedQueries({
#NamedQuery(name = "Items.findAll", query = "SELECT i FROM Items i"),
#NamedQuery(name = "Items.findByItemid", query = "SELECT i FROM Items i WHERE i.itemid = :itemid"),
#NamedQuery(name = "Items.findByItemName", query = "SELECT i FROM Items i WHERE i.itemName = :itemName"),
#NamedQuery(name = "Items.findByItemDescribe", query = "SELECT i FROM Items i WHERE i.itemDescribe = :itemDescribe"),
#NamedQuery(name = "Items.findByImg", query = "SELECT i FROM Items i WHERE i.img = :img"),
#NamedQuery(name = "Items.findByInstock", query = "SELECT i FROM Items i WHERE i.instock = :instock"),
#NamedQuery(name = "Items.findByPrice", query = "SELECT i FROM Items i WHERE i.price = :price"),
#NamedQuery(name = "Items.findByFine", query = "SELECT i FROM Items i WHERE i.fine = :fine"),
#NamedQuery(name = "Items.findByDateexp", query = "SELECT i FROM Items i WHERE i.dateexp = :dateexp"),
#NamedQuery(name = "Items.findByAuthor", query = "SELECT i FROM Items i WHERE i.author = :author"),
#NamedQuery(name = "Items.findByToprent", query = "SELECT i FROM Items i WHERE i.toprent = :toprent"),
#NamedQuery(name = "Items.findByStatus", query = "SELECT i FROM Items i WHERE i.status = :status")})
public class Items implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "itemid")
private Integer itemid;
#Basic(optional = false)
#Column(name = "item_name")
private String itemName;
#Column(name = "item_describe")
private String itemDescribe;
#Lob
#Column(name = "item_detail")
private String itemDetail;
#Column(name = "img")
private String img;
#Basic(optional = false)
#Column(name = "instock")
private int instock;
#Basic(optional = false)
#Column(name = "price")
private BigDecimal price;
#Basic(optional = false)
#Column(name = "fine")
private BigDecimal fine;
#Basic(optional = false)
#Column(name = "dateexp")
private int dateexp;
#Column(name = "author")
private String author;
#Column(name = "toprent")
private Integer toprent;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private ItemStatus status;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<RentItem> rentItemList;
#JoinColumn(name = "cat_id", referencedColumnName = "subcatid")
#ManyToOne(optional = false)
private SubCat subCat;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<Cart> cartList;
public Items() {
}
public Items(Integer itemid) {
this.itemid = itemid;
}
public Items(Integer itemid, String itemName, int instock, BigDecimal price, BigDecimal fine, int dateexp) {
this.itemid = itemid;
this.itemName = itemName;
this.instock = instock;
this.price = price;
this.fine = fine;
this.dateexp = dateexp;
}
public Integer getItemid() {
return itemid;
}
public void setItemid(Integer itemid) {
this.itemid = itemid;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescribe() {
return itemDescribe;
}
public void setItemDescribe(String itemDescribe) {
this.itemDescribe = itemDescribe;
}
public String getItemDetail() {
return itemDetail;
}
public void setItemDetail(String itemDetail) {
this.itemDetail = itemDetail;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getInstock() {
return instock;
}
public void setInstock(int instock) {
this.instock = instock;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getFine() {
return fine;
}
public void setFine(BigDecimal fine) {
this.fine = fine;
}
public int getDateexp() {
return dateexp;
}
public void setDateexp(int dateexp) {
this.dateexp = dateexp;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getToprent() {
return toprent;
}
public void setToprent(Integer toprent) {
this.toprent = toprent;
}
public ItemStatus getStatus() {
return status;
}
public void setStatus(ItemStatus status) {
this.status = status;
}
public List<RentItem> getRentItemList() {
return rentItemList;
}
public void setRentItemList(List<RentItem> rentItemList) {
this.rentItemList = rentItemList;
}
public SubCat getSubCat() {
return subCat;
}
public void setSubCat(SubCat subCat) {
this.subCat = subCat;
}
public List<Cart> getCartList() {
return cartList;
}
public void setCartList(List<Cart> cartList) {
this.cartList = cartList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (itemid != null ? itemid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Items)) {
return false;
}
Items other = (Items) object;
if ((this.itemid == null && other.itemid != null) || (this.itemid != null && !this.itemid.equals(other.itemid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Item[itemid=" + itemid + "]";
}
}
and subcategory class :
#Entity
#Table(name = "sub_cat")
#NamedQueries({
#NamedQuery(name = "SubCat.findAll", query = "SELECT s FROM SubCat s"),
#NamedQuery(name = "SubCat.findBySubcatid", query = "SELECT s FROM SubCat s WHERE s.subcatid = :subcatid"),
#NamedQuery(name = "SubCat.findBySubcatName", query = "SELECT s FROM SubCat s WHERE s.subcatName = :subcatName")})
public class SubCat implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "subcatid")
private Integer subcatid;
#Basic(optional = false)
#Column(name = "subcat_name")
private String subcatName;
#JoinColumn(name = "cat_parent", referencedColumnName = "cate_id")
#ManyToOne(optional = false)
private Category category;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "subCat")
private List<Items> itemList;
public SubCat() {
}
public SubCat(Integer subcatid) {
this.subcatid = subcatid;
}
public SubCat(Integer subcatid, String subcatName) {
this.subcatid = subcatid;
this.subcatName = subcatName;
}
public Integer getSubcatid() {
return subcatid;
}
public void setSubcatid(Integer subcatid) {
this.subcatid = subcatid;
}
public String getSubcatName() {
return subcatName;
}
public void setSubcatName(String subcatName) {
this.subcatName = subcatName;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Items> getItemList() {
return itemList;
}
public void setItemList(List<Items> itemList) {
this.itemList = itemList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (subcatid != null ? subcatid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SubCat)) {
return false;
}
SubCat other = (SubCat) object;
if ((this.subcatid == null && other.subcatid != null) || (this.subcatid != null && !this.subcatid.equals(other.subcatid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.SubCat[subcatid=" + subcatid + "]";
}
}
i have stateless bean for handle subcat such as:
#Stateless
#LocalBean
public class SubCatDAO {
#PersistenceContext(unitName = "mcGrawLibPro-ejbPU")
private EntityManager em;
public List<SubCat> retrieveAllSubCat(){
return em.createNamedQuery("SubCat.findAll").getResultList();
}
public SubCat updateSubCat(SubCat sc){
return em.merge(sc);
}
public void deleteSubCat(SubCat sc){
em.remove(em.merge(sc));
}
public SubCat addSubCat(SubCat sc){
em.persist(sc);
return sc;
}
public void persist(Object object) {
em.persist(object);
}
public List<Category> retrieveAllCat(){
return em.createNamedQuery("Category.findAll").getResultList();
}
public List<Items> getAllItemsSubCat(SubCat sub){
em.refresh(em.merge(sub));
List<Items> items = sub.getItemList();
ArrayList<Items> toReturn = new ArrayList<Items>(items.size());
for(Items iItem : items){
toReturn.add(iItem);
}
return toReturn;
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
as you can see in stateless bean of subcat , i have written one method return List
and in JSF Managed Bean of subcat i write one method return List to view (JSF)
such as:
public List<Items> getAllItemsSub(){
return subCatDAO.getAllItemsSubCat(sub);
}
(subCatDAO is Stateless bean)
also in JSF Managened Bean of subcat i inital subcat follow:
public BeanConstructor(){
sub = new SubCat(1);
}
my problem is in view (JSF ) i was print list of items to show to user , but i can't get anything,i just see blank,
my code sample :
<h:ouputText value="#{bean.allItemSub.itemid}"/>
when i print bean.allItemSub it return [] <===
why it empty?
I don't really understand your implementation of the getAllItemsSubCat(SubCat sub) method in your EJB. I would rewrite it like this.
First, add a named query to find Items for given a SubCategory:
#NamedQuery(name = "Items.findBySubCat",
query = "SELECT i FROM Items i WHERE i.subCat = :subCat")
And rewrite the EJB method as follow:
public List<Items> getAllItemsSubCat(SubCat sub){
return em.createNamedQuery("Items.findBySubCat").setParameter("subCat", sub)
.getResultList();
}
Then, activate SQL logging (at the JPA provider level) to make sure the method actually returns something.
Exception
java.lang.IllegalArgumentException: partidosPK.idEquipo
at javax.faces.component.UIComponentBase.validateId(UIComponentBase.java:551)
at javax.faces.component.UIComponentBase.setId(UIComponentBase.java:366)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply (ComponentTagHandlerDelegateImpl.java:168)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:114)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:91)
at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:120)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:204)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:114)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:91)
at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:120)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:204)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:114)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:91)
at com.sun.faces.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:97)
at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:172)
and keeps going... also
Entity bean
private String ganador;
#Column(name = "fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date fecha;
#Column(name = "golesEquipoGanador")
private Integer golesEquipoGanador;
#Column(name = "golesEquipoPerdedor")
private Integer golesEquipoPerdedor;
#Column(name = "perdedor")
private String perdedor;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "partidos")
private Collection<Goleadores> goleadoresCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "partidos")
private Collection<SancionesJugadores> sancionesJugadoresCollection;
#JoinColumns({
#JoinColumn(name = "idCampeonato", referencedColumnName = "idCampeonato", insertable = false, updatable = false),
#JoinColumn(name = "idPartido", referencedColumnName = "idEquipo", insertable = false, updatable = false)})
#ManyToOne(optional = false)
private EquiposPorCampeonato equiposPorCampeonato;
public Partidos() {
}
public Partidos(PartidosPK partidosPK) {
this.partidosPK = partidosPK;
}
public Partidos(int idCampeonato, int idEquipo, int idPartido) {
this.partidosPK = new PartidosPK(idCampeonato, idEquipo, idPartido);
}
public PartidosPK getPartidosPK() {
return partidosPK;
}
public void setPartidosPK(PartidosPK partidosPK) {
this.partidosPK = partidosPK;
}
public String getGanador() {
return ganador;
}
public void setGanador(String ganador) {
this.ganador = ganador;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Integer getGolesEquipoGanador() {
return golesEquipoGanador;
}
public void setGolesEquipoGanador(Integer golesEquipoGanador) {
this.golesEquipoGanador = golesEquipoGanador;
}
public Integer getGolesEquipoPerdedor() {
return golesEquipoPerdedor;
}
public void setGolesEquipoPerdedor(Integer golesEquipoPerdedor) {
this.golesEquipoPerdedor = golesEquipoPerdedor;
}
public String getPerdedor() {
return perdedor;
}
public void setPerdedor(String perdedor) {
this.perdedor = perdedor;
}
public Collection<Goleadores> getGoleadoresCollection() {
return goleadoresCollection;
}
public void setGoleadoresCollection(Collection<Goleadores> goleadoresCollection) {
this.goleadoresCollection = goleadoresCollection;
}
public Collection<SancionesJugadores> getSancionesJugadoresCollection() {
return sancionesJugadoresCollection;
}
public void setSancionesJugadoresCollection(Collection<SancionesJugadores> sancionesJugadoresCollection) {
this.sancionesJugadoresCollection = sancionesJugadoresCollection;
}
public EquiposPorCampeonato getEquiposPorCampeonato() {
return equiposPorCampeonato;
}
public void setEquiposPorCampeonato(EquiposPorCampeonato equiposPorCampeonato) {
this.equiposPorCampeonato = equiposPorCampeonato;
}
#Override
public int hashCode() {
int hash = 0;
hash += (partidosPK != null ? partidosPK.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Partidos)) {
return false;
}
Partidos other = (Partidos) object;
if ((this.partidosPK == null && other.partidosPK != null) || (this.partidosPK != null && !this.partidosPK.equals(other.partidosPK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "" + partidosPK + "";
}
}
related primaryKey entitybean
#Embeddable
public class PartidosPK implements Serializable {
#Basic(optional = false)
#Column(name = "idCampeonato")
private int idCampeonato;
#Basic(optional = false)
#Column(name = "idEquipo")
private int idEquipo;
#Basic(optional = false)
#Column(name = "idPartido")
private int idPartido;
public PartidosPK() {
}
public PartidosPK(int idCampeonato, int idEquipo, int idPartido) {
this.idCampeonato = idCampeonato;
this.idEquipo = idEquipo;
this.idPartido = idPartido;
}
public int getIdCampeonato() {
return idCampeonato;
}
public void setIdCampeonato(int idCampeonato) {
this.idCampeonato = idCampeonato;
}
public int getIdEquipo() {
return idEquipo;
}
public void setIdEquipo(int idEquipo) {
this.idEquipo = idEquipo;
}
public int getIdPartido() {
return idPartido;
}
public void setIdPartido(int idPartido) {
this.idPartido = idPartido;
}
#Override
public int hashCode() {
int hash = 0;
hash += (int) idCampeonato;
hash += (int) idEquipo;
hash += (int) idPartido;
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PartidosPK)) {
return false;
}
PartidosPK other = (PartidosPK) object;
if (this.idCampeonato != other.idCampeonato) {
return false;
}
if (this.idEquipo != other.idEquipo) {
return false;
}
if (this.idPartido != other.idPartido) {
return false;
}
return true;
}
#Override
public String toString() {
return "" + idCampeonato + ", " + idEquipo + ", " + idPartido + "";
}
}
Last but not least
#Entity
#Table(name = "equipos")
#NamedQueries({
#NamedQuery(name = "Equipos.findAll", query = "SELECT e FROM Equipos e"),
#NamedQuery(name = "Equipos.findByIdEquipo", query = "SELECT e FROM Equipos e WHERE e.idEquipo = :idEquipo"),
#NamedQuery(name = "Equipos.findByNombre", query = "SELECT e FROM Equipos e WHERE e.nombre = :nombre")})
public class Equipos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idEquipo")
private Integer idEquipo;
#Basic(optional = false)
#Column(name = "nombre")
private String nombre;
#JoinColumn(name = "idSexo", referencedColumnName = "idSexo")
#ManyToOne(optional = false)
private Sexos idSexo;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idEquipo")
private Collection<Jugadores> jugadoresCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "equipos")
private Collection<EquiposPorCampeonato> equiposPorCampeonatoCollection;
public Equipos() {
}
public Equipos(Integer idEquipo) {
this.idEquipo = idEquipo;
}
public Equipos(Integer idEquipo, String nombre) {
this.idEquipo = idEquipo;
this.nombre = nombre;
}
public Integer getIdEquipo() {
return idEquipo;
}
public void setIdEquipo(Integer idEquipo) {
this.idEquipo = idEquipo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Sexos getIdSexo() {
return idSexo;
}
public void setIdSexo(Sexos idSexo) {
this.idSexo = idSexo;
}
public Collection<Jugadores> getJugadoresCollection() {
return jugadoresCollection;
}
public void setJugadoresCollection(Collection<Jugadores> jugadoresCollection) {
this.jugadoresCollection = jugadoresCollection;
}
public Collection<EquiposPorCampeonato> getEquiposPorCampeonatoCollection() {
return equiposPorCampeonatoCollection;
}
public void setEquiposPorCampeonatoCollection(Collection<EquiposPorCampeonato> equiposPorCampeonatoCollection) {
this.equiposPorCampeonatoCollection = equiposPorCampeonatoCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idEquipo != null ? idEquipo.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Equipos)) {
return false;
}
Equipos other = (Equipos) object;
if ((this.idEquipo == null && other.idEquipo != null) || (this.idEquipo != null && !this.idEquipo.equals(other.idEquipo))) {
return false;
}
return true;
}
#Override
public String toString() {
return "" + nombre + "";
}
}
Table scripts available if needed
Thank you very much.
Yes its spanish please bear with me!
Equipos == Teams;
Partidos == Matches;
Campeonatos == Championships;
This exception is related to the view, not to the model. The exception is telling that you've set a component ID with the value partidosPK.idEquipo like as follows:
<h:someComponent id="partidosPK.idEquipo">
However, this ID is illegal as per the rules. It contains a dot .. Remove it or replace by _ or -. The rules are the same as for the HTML/CSS identifiers.
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit.