How to pass parameters to Primefaces LazyDataModel load function - jsf

I have a implemented a lazy loading Datatable with primefaces that implements
load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters)
Now I need to pass parameters from my page to this method (i.e., I have a filter section in my page, the filters are not part of the table, and are independent objects!). My parameters are stored in the page's managed bean.
How can I achieve this?
Thanks!

Make the parameter(s) a property of the bean, and pass them directly to the service that fetches the data from the db (in this example the service is the EJB MyObjFacade myObjFacade):
#ManagedBean
#ViewScoped
public class MyBean {
#EJB
private MyObjFacade myObjFacade;
private LazyDataModel<MyObjType> model; // getter
private MyParameter myParameter;
#PostConstruct
public void init() {
model = new LazyDataModel<MyObjType> () {
#Override
public List<MyObjType> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
model.setRowCount(myObjFacade.count(filters, myParameter));
return myObjFacade.getResultList(first, pageSize, sortField, sortOrder, filters, myParameter);
}
};
model.setRowCount(myObjFacade.count(new HashMap<String, String> ()));
}
}
You simply have to provide the service implementing count and getResultList methods.

After many hours searching I finally did it. I leave here my solution for further reference.
//Managed Bean - View
public class DummyLazySearchPageBean {
private LazyDataModel<DummyObject> results;
private String searchFilter;//to simulate search filter
private DummyBusinessClass dummyBusinessClass;
public DummyLazySearchPageBean() {
results = new SearchsLazyLoader();
}
// GETTERS AND SETTERS
#SuppressWarnings("serial")
private final class SearchsLazyLoader extends LazyDataModel<DummyObject> {
#Override
public List<DummyObject> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
//Simulate BD model
List<DummyObject> data = new ArrayList<DummyObject>();
dummyBusinessClass = new DummyBusinessClass();
data = dummyBusinessClass.search(searchFilter, 5000);
//rowCount
this.setRowCount(data.size());
//paginate
if(data.size() > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (data.size() % pageSize));
}
}
else {
return data;
}
}
}
public final void search(){
results = new SearchsLazyLoader();
}
}

Just Create Constructor of SearchsLazyLoader with parameter input.
This is sample of my code:
package com.mandiri.askes.model.lazy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import com.mandiri.askes.model.Participant;
import com.mandiri.askes.utils.CallAble;
import com.mandiri.askes.utils.HibernateUtil;
public class LazyPesertaDataModel extends LazyDataModel<Participant> {
private static final long serialVersionUID = 1L;
private String keyword;
public LazyPesertaDataModel(String keyword) {
if (StringUtils.isNotEmpty(keyword)) {
this.keyword = keyword;
}else{
this.keyword = "";
}
}
/**
* Collect Peserta Badan Usaha as Data Model Primefaces
*
*/
#Override
public List<Participant> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters) {
List<Participant> listPesertaBpjs = new ArrayList<Participant>();
listPesertaBpjs = getLazyDataPeserta(first, pageSize, sortField);
this.setRowCount(countAllRecord());
return listPesertaBpjs;
}
/**
* Get Peserta Data using hibernate pagination <b>(Lazy Loading)</b> Technique.
*
* #author Dibrut
* #param firstRecord
* #param maxResult
* #return
*/
#SuppressWarnings("unchecked")
public List<Participant> getLazyDataPeserta(final int firstRecord, final int maxResult, final String sortField) {
return HibernateUtil.doInTransaction(new CallAble<List<Participant>>() {
#Override
public List<Participant> call(Session session) throws Exception {
List<Participant> pesertaList = new ArrayList<Participant>();
String hql = "FROM com.dibrut.learn.model.Participant P"
+ " WHERE P.name LIKE :keyword";
Query query = session.createQuery(hql).setFirstResult(firstRecord).
setMaxResults(maxResult).setString("keyword", "%"+keyword+"%");
pesertaList = query.list();
return pesertaList;
}
});
}
/**
* Count total participant
* #return
* #author Dibrut
*/
public int countAllRecord(){
return HibernateUtil.doInTransaction(new CallAble<Integer>() {
#Override
public Integer call(Session session) throws Exception {
String hql = "FROM com.dibrut.learn.model.Participant P"
+ " WHERE P.name LIKE :keyword";
Long totalPesertaBu = (Long) session.createQuery(hql).
setString("keyword", "%"+ keyword+"%").
uniqueResult();
return totalPesertaBu.intValue();
}
});
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
if you want to search the data, just call the constructor with parameter of your managedBean property. for example you have searchParticipant method in your ManagedBean:
public void searchParticipant() {
this.participantLazyModel = new LazyPesertaDataModel(this.keyword);
}
where the keyword is value of inputText from your page.

Related

JAXB: using #XmlID along with Hibernate #Id

I have following hibernate property:
#Id()
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id = null;
I want to add JAXB annotation #XmlID to this id but #XmlID can only be applied to String data types. How can I solve this problem.
#XmlID
#Transient
public String getXId(){
return this.id;
}
public String setXId(String s){
this.id = Long.parseDouble(s);
}
Use #XmlJavaTypeAdapter(IDAdapter.class) along with #XmlID where IDAdapter is
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class IDAdapter extends XmlAdapter<String, Long> {
#Override
public Long unmarshal(String string) throws Exception {
return DatatypeConverter.parseLong(string);
}
#Override
public String marshal(Long value) throws Exception {
return DatatypeConverter.printLong(value);
}
}

p:orderList converter getAsObject() doesn't call Object.toString()

I've written a custom converter as follows:
#FacesConverter(value = "orderListConverter")
public class OrderListConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
Object ret = null;
if (component instanceof OrderList) {
Object list = ((OrderList) component).getValue();
ArrayList<ExampleEntity> al = (ArrayList<ExampleEntity>) list;
for (Object o : al) {
String name = "" + ((ExampleEntity) o).getName();
if (value.equals(name)) {
ret = o;
break;
}
}
}
return ret;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
String str = "";
if (value instanceof ExampleEntity) {
str = "" + ((ExampleEntity) value).getNumber();
}
return str;
}
}
My ExampleEntity is implemented as follows:
public class ExampleEntity {
private String name;
private int number;
public ExampleEntity(String name, int number) {
this.name = name;
this.number = number;
}
#Override
public String toString() {
return "toString(): [name=" + name + ", number=" + number + "]";
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
the orderList-Component from Primefaces looks like that:
<p:orderList value="#{orderListBean.exampleList}"
var="exampleEntity" itemValue="#{exampleEntity}"
converter="orderListConverter">
<p:column style="width:25%">
#{exampleEntity.number}
</p:column>
<p:column style="width:75%;">
#{exampleEntity.name}
</p:column>
</p:orderList>
and the bean is implemented as follows:
#SessionScoped
#ManagedBean(name = "orderListBean")
public class OrderListBean {
private List<ExampleEntity> exampleList;
#PostConstruct
public void init() {
exampleList = new ArrayList<ExampleEntity>();
exampleList.add(new ExampleEntity("nameOne", 1));
exampleList.add(new ExampleEntity("nameTwo", 2));
exampleList.add(new ExampleEntity("nameThree", 3));
exampleList.add(new ExampleEntity("nameFour", 4));
exampleList.add(new ExampleEntity("nameFive", 5));
}
public List<ExampleEntity> getExampleList() {
return exampleList;
}
public void setExampleList(List<ExampleEntity> exampleList) {
this.exampleList = exampleList;
}
}
1) when debugging, the value Parameter of getAsObject() contains
the number of the ExampleEntity, but I had expected the
toString() method of ExampleEntity to be called!
2) What is the correct content for itemValue attribute?
Is it a kind of convention over configuration? Or how does the component
'know', to use the whole object, when inserting exampleEntity into itemValue
Hope everything is clear! Tanks a lot for any explanation!
Converters basically serve to transform values in 2 directions:
Server to client, when the value is rendered.
Client to server, when the value is submitted.
In your getAsString you established, that the string representation, the one which client uses, is exampleEntity's number. So that's what gets rendered to client as a value. And later, when the client submits its value, that value is number. To convert it to the object (server) representation, the getAsObject called with the number as a parameter.
The server can't possibly call getAsObject with exampleEntity.toString(), because it doesn't have the exampleEntity instance at that point, only the submitted number.
To illustrate, this should hold:
obj.equals(conv.getAsObject(ctx, comp, conv.getAsString(ctx, comp, obj)));
getAsObject and getAsString should be inversive in their input and output.
To answer your 2nd question: that depends on your needs. You could say itemValue="#{exampleEntity.number}", but that would make sense only if you're not interested in the exampleEntity itself, i.e. on submit you would get the number from the client and that's all you need for your server-side logic.
#FacesConverter(value = "EntityConverter")
public class EntityConverter implements Converter, Serializable {
private static final long serialVersionUID = 1L;
public EntityConverter() {
super();
}
#Override
public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {
if (value == null) {
return null;
}
return fromSelect(component, value);
}
/**
* #param currentcomponent
* #param objectString
* #return the Object
*/
private Object fromSelect(final UIComponent currentcomponent, final String objectString) {
if (currentcomponent.getClass() == UISelectItem.class) {
final UISelectItem item = (UISelectItem) currentcomponent;
final Object value = item.getValue();
if (objectString.equals(serialize(value))) {
return value;
}
}
if (currentcomponent.getClass() == UISelectItems.class) {
final UISelectItems items = (UISelectItems) currentcomponent;
final List<Object> elements = (List<Object>) items.getValue();
for (final Object element : elements) {
if (objectString.equals(serialize(element))) {
return element;
}
}
}
if (!currentcomponent.getChildren().isEmpty()) {
for (final UIComponent component : currentcomponent.getChildren()) {
final Object result = fromSelect(component, objectString);
if (result != null) {
return result;
}
}
}
if (currentcomponent instanceof OrderList) {
Object items = ((OrderList) currentcomponent).getValue();
List<Object> elements = (List<Object>) items;
for (final Object element : elements) {
if (objectString.equals(serialize(element))) {
return element;
}
}
}
return null;
}
/**
* #param object
* #return the String
*/
private String serialize(final Object object) {
if (object == null) {
return null;
}
return object.getClass() + "#" + object.hashCode();
}
#Override
public String getAsString(final FacesContext arg0, final UIComponent arg1, final Object object) {
return serialize(object);
}
}

Why Cassandra throwing com.datastax.driver.core.exceptions.InvalidQueryException: Multiple definitions found for column

Context:
I am running a jUnit test in eclipse by using embedded Cassandra to test my DAO class which is using an Astyanax client configured for JavaDriver. When DAO object instance insert into Cassandra I am getting this exception com.datastax.driver.core.exceptions.InvalidQueryException: Multiple definitions found for column ..columnname
TestClass
public class LeaderBoardDaoTest {
private static LeaderBoardDao dao;
public static CassandraCQLUnit cassandraCQLUnit;
private String hostIp = "127.0.0.1";
private int port = 9142;
public Session session;
public Cluster cluster;
#BeforeClass
public static void startCassandra() throws IOException, TTransportException, ConfigurationException, InterruptedException {
System.setProperty("archaius.deployment.applicationId", "leaderboardapi");
System.setProperty("archaius.deployment.environment", "test");
EmbeddedCassandraServerHelper.startEmbeddedCassandra("cassandra.yaml");
// cassandraCQLUnit = new CassandraCQLUnit(new
// ClassPathCQLDataSet("simple.cql", "lbapi"), "cassandra.yaml");
Injector injector = Guice.createInjector(new TestModule());
dao = injector.getInstance(LeaderBoardDao.class);
}
#Before
public void load() {
cluster = new Cluster.Builder().withClusterName("leaderboardcassandra").addContactPoints(hostIp).withPort(port).build();
session = cluster.connect();
CQLDataLoader dataLoader = new CQLDataLoader(session);
dataLoader.load(new ClassPathCQLDataSet("simple.cql", "lbapi"));
session = dataLoader.getSession();
}
#Test
public void test() {
ResultSet result = session.execute("select * from mytable WHERE id='myKey01'");
Assert.assertEquals(result.iterator().next().getString("value"), "myValue01");
}
#Test
public void testInsert() {
LeaderBoard lb = new LeaderBoard();
lb.setName("name-1");
lb.setDescription("description-1");
lb.setActivityType(ActivityType.FUEL);
lb.setImage("http:/");
lb.setLbId(UUID.fromString("3F2504E0-4F89-41D3-9A0C-0305E82C3301"));
lb.setStartTime(new Date());
lb.setEndTime(new Date());
dao.insert(lb);
ResultSet resultSet = session.execute("select * from leaderboards WHERE leaderboardid='3F2504E0-4F89-41D3-9A0C-0305E82C3301'");
}
#After
public void clearCassandra() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
#AfterClass
public static void stopCassandra() {
EmbeddedCassandraServerHelper.stopEmbeddedCassandra();
}
}
Class under test
#Singleton
public class LeaderBoardDao {
private static final Logger log = LoggerFactory.getLogger(LeaderBoardDao.class);
#Inject
private AstyanaxMutationsJavaDriverClient client;
private static final String END_TIME = "end_time";
private static final String START_TIME = "start_time";
private static final String IMAGE = "image";
private static final String ACTIVITY_TYPE = "activity_type";
private static final String DESCRIPTION = "description";
private static final String NAME = "name";
private static final String LEADERBOARD_ID = "leaderboardID";
private static final String COLUMN_FAMILY_NAME = "leaderboards";
private ColumnFamily<UUID, String> cf;
public LeaderBoardDao() throws ConnectionException {
cf = ColumnFamily.newColumnFamily(COLUMN_FAMILY_NAME, UUIDSerializer.get(), StringSerializer.get());
}
/**
* Writes the Leaderboard to the database.
*
* #param lb
*/
public void insert(LeaderBoard lb) {
try {
MutationBatch m = client.getKeyspace().prepareMutationBatch();
cf.describe(client.getKeyspace());
m.withRow(cf, lb.getLbId()).putColumn(LEADERBOARD_ID, UUIDUtil.asByteArray(lb.getLbId()), null).putColumn(NAME, lb.getName(), null).putColumn(DESCRIPTION, lb.getDescription(), null)
.putColumn(ACTIVITY_TYPE, lb.getActivityType().name(), null).putColumn(IMAGE, lb.getImage()).putColumn(START_TIME, lb.getStartTime()).putColumn(END_TIME, lb.getEndTime());
m.execute();
} catch (ConnectionException e) {
Throwables.propagate(e);
}
}
/**
* Reads leaderboard from database
*
* #param id
* #return {#link LeaderBoard}
*/
public LeaderBoard read(UUID id) {
OperationResult<ColumnList<String>> result;
LeaderBoard lb = null;
try {
result = client.getKeyspace().prepareQuery(cf).getKey(id).execute();
ColumnList<String> cols = result.getResult();
if (!cols.isEmpty()) {
lb = new LeaderBoard();
lb.setLbId(cols.getUUIDValue(LEADERBOARD_ID, null));
lb.setName(cols.getStringValue(NAME, null));
lb.setActivityType(ActivityType.valueOf(cols.getStringValue(ACTIVITY_TYPE, null)));
lb.setDescription(cols.getStringValue(DESCRIPTION, null));
lb.setEndTime(cols.getDateValue(END_TIME, null));
lb.setStartTime(cols.getDateValue(START_TIME, null));
lb.setImage(cols.getStringValue(IMAGE, null));
} else {
log.warn("read: is empty: no record found for " + id);
}
return lb;
} catch (ConnectionException e) {
log.error("failed to read from C*", e);
throw new RuntimeException("failed to read from C*", e);
}
}
}
When the Java driver throws an InvalidQueryException, it's rethrowing an error from Cassandra. The error "Multiple definitions found for column..." indicates that a column is mentioned more than once in an update statement. You can simulate it in cqlsh:
cqlsh> create table test(i int primary key);
cqlsh> insert into test (i, i) values (1, 2);
code=2200 [Invalid query] message="Multiple definitions found for column i"
I'm not familiar with Astyanax, but my guess is that it already adds the id to the query when you call withRow, so you don't need to add it again with putColumn. Try removing that call (second line in reformatted sample below):
m.withRow(cf, lb.getLbId())
.putColumn(LEADERBOARD_ID, UUIDUtil.asByteArray(lb.getLbId()), null)
... // other putColumn calls

JSF h:selectonemenu convertor Validation error value is not valid [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I know this has been discussed a lot, and I also tried most of resolution, but I still got this error:
sourceId=comboNewTaskParent[severity=(ERROR 2), summary=(comboNewTaskParent: Validation Error: Value is not valid), detail=(comboNewTaskParent: Validation Error: Value is not valid)]
Here is the code for HTML:
<h:outputLabel value="Parent task" for="comboNewTaskParent" />
<div class="formRight">
<h:selectOneMenu id="comboNewTaskParent" value="#{taskController.parentTask}" converter="#{taskConverter}"
<f:selectItems value="#{comboTaskByProject}" var="task" itemValue="#{task}" itemLabel="#{task.taskName}" />
</h:selectOneMenu>
</div>
Here is the code of my entity bean:
package com.projectportal.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the Task database table.
*
*/
#Entity
#Table(name="Task")
public class Task implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(unique=true, nullable=false, length=36)
private String taskId;
#Column(length=1000)
private String taskDesc;
#Column(nullable=false)
private int taskDurationHour;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable=false)
private Date taskEstimated;
#Column(nullable=false, length=200)
private String taskName;
#Column(nullable=false)
private float taskPercentComplete;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable=false)
private Date taskStartDate;
//bi-directional many-to-one association to Priority
#ManyToOne
#JoinColumn(name="priorityId", nullable=false)
private Priority priority;
//bi-directional many-to-one association to Project
#ManyToOne
#JoinColumn(name="projectId")
private Project project;
//bi-directional many-to-one association to Status
#ManyToOne
#JoinColumn(name="statusId", nullable=false)
private Status status;
//bi-directional many-to-one association to Task
#ManyToOne
#JoinColumn(name="parentTaskId")
private Task parentTask;
//bi-directional many-to-one association to Task
#OneToMany(mappedBy="parentTask")
private List<Task> childTasks;
//bi-directional many-to-one association to Task
#ManyToOne
#JoinColumn(name="preTaskId")
private Task preTask;
//bi-directional many-to-one association to Task
#OneToMany(mappedBy="preTask")
private List<Task> dependentTasks;
//bi-directional many-to-one association to UserXTask
#OneToMany(mappedBy="task")
private List<UserXTask> userXtasks;
public Task() {
}
public String getTaskId() {
return this.taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskDesc() {
return this.taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public int getTaskDurationHour() {
return this.taskDurationHour;
}
public void setTaskDurationHour(int taskDurationHour) {
this.taskDurationHour = taskDurationHour;
}
public Date getTaskEstimated() {
return this.taskEstimated;
}
public void setTaskEstimated(Date taskEstimated) {
this.taskEstimated = taskEstimated;
}
public String getTaskName() {
return this.taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public float getTaskPercentComplete() {
return this.taskPercentComplete;
}
public void setTaskPercentComplete(float taskPercentComplete) {
this.taskPercentComplete = taskPercentComplete;
}
public Date getTaskStartDate() {
return this.taskStartDate;
}
public void setTaskStartDate(Date taskStartDate) {
this.taskStartDate = taskStartDate;
}
public Priority getPriority() {
return this.priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Project getProject() {
return this.project;
}
public void setProject(Project project) {
this.project = project;
}
public Status getStatus() {
return this.status;
}
public void setStatus(Status status) {
this.status = status;
}
public Task getParentTask() {
return this.parentTask;
}
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
public List<Task> getChildTasks() {
return this.childTasks;
}
public void setChildTasks(List<Task> childTasks) {
this.childTasks = childTasks;
}
public Task getPreTask() {
return this.preTask;
}
public void setPreTask(Task preTask) {
this.preTask = preTask;
}
public List<Task> getDependentTasks() {
return this.dependentTasks;
}
public void setDependentTasks(List<Task> dependentTasks) {
this.dependentTasks = dependentTasks;
}
public List<UserXTask> getUserXtasks() {
return this.userXtasks;
}
public void setUserXtasks(List<UserXTask> userXtasks) {
this.userXtasks = userXtasks;
}
}
The controller:
public #Model class TaskController {
#Inject private EntityManager em;
#Inject Identity identity;
#Inject Logger log;
#Inject Event<Task> taskEventSrc;
#Named
#Produces
private List<Task> requestTaskList;
private Task parentTask;
private Task newTask;
#Produces
#Named
public Task getNewTask(){
return this.newTask;
}
/**
*
*/
public TaskController() {
// TODO Auto-generated constructor stub
}
#PostConstruct
public void loadSelfTasks(){
// Init
newTask = new Task();
// Get user from DB.
User user = em.find(User.class, identity.getUser().getId());
requestTaskList = new ArrayList<Task>();
// Loop user's tasks.
for(UserXTask userTask : user.getUserXtasks()){
requestTaskList.add(userTask.getTask());
}
log.info("Tasks for user: " + user.getFirstname() + " loaded.");
}
/**
* Create task.
* #throws Exception
*/
public void createTask() throws Exception{
log.info("Persistencing task: " + newTask.getParentTask().getTaskId());
em.persist(newTask);
taskEventSrc.fire(newTask);
newTask = new Task();
}
/**
* #return the parentTask
*/
public Task getParentTask() {
return parentTask;
}
/**
* #param parentTask the parentTask to set
*/
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
}
And of course the converter:
#Named
/**
* #author lastcow
*
*/
public class TaskConverter implements Converter {
#Inject EntityManager em;
#Inject Logger log;
/* (non-Javadoc)
* #see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
*/
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
log.info("=========== Convert to Object " + value);
if(value.equals("0")){
return null;
}
Task t = em.find(Task.class, value);
log.info("======== Got : " + t.getTaskName());
return t;
}
/* (non-Javadoc)
* #see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
*/
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
log.info("=========== Convert to String " + value);
return ((Task)value).getTaskId();
}
}
from what logged, the convert are working as it, but when I try to submit the form, always throw 'Validation Error: Value is not valid' ERROR, I have struck here for almost 2 days.
Anyone please give some suggestions.
BTW, I tried put equals and hashCode in Task.java, doesn't working either.
Thanks in advance.
Validation Error: Value is not valid
This error will be thrown when the equals() method of the selected item hasn't returned true for any of the available items in <f:selectItem(s)>. Thus, this can technically have only 2 causes:
The equals() method of your Task class is missing or broken.
The <f:selectItems value="#{comboTaskByProject}"> has incompatibly changed during the postback request of the form submit as compared to during the initial request of the form display.
To fix cause #1, make sure that you understand how to implement equals() properly. You can find kickoff examples here: Right way to implement equals contract
To fix cause #2, make sure that the #{comboTaskByProject} never canges during postback. Best is to put it in the view scope or broader, or to make sure that request based conditions for populating that list are preserved in the postback request by e.g. using <f:viewParam>.
See also:
Our selectOneMenu wiki page
Validation Error: Value is not valid
I am not sure which version of JSF you are using. As far as I know, the converter in HTML should be used like this converter="javax.faces.DateTime". Where this part javax.faces.DateTime is converter name defined in faces-config.xml or in converter class with #FacesConverter.

jpql Join query

i have an association table called MenuPrevilege between 2 tables called Menu and Previlege.
In order to get all menus of a specific previlege i created a named query in the Menu entity:
#Entity
#NamedQueries( {
#NamedQuery(name = "getAllMenus", query = "select m from Menu m"),
#NamedQuery(name = "getMenusByPrevilegeId", query = "select m from Menu m
JOIN m.menuPrevilege mp where mp.previlege_id = :p")})
public class Menu implements Serializable {
private String url;
private String description;
private List<MenuPrevilege> menuPrevilges;
private static final long serialVersionUID = 1L;
public Menu() {
super();
}
#Id
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public void setMenuPrevilges(List<MenuPrevilege> menuPrevilges) {
if (menuPrevilges == null)
menuPrevilges = new ArrayList<MenuPrevilege>();
this.menuPrevilges = menuPrevilges;
}
#OneToMany(mappedBy = "menu", cascade = CascadeType.REMOVE)
public List<MenuPrevilege> getMenuPrevilges() {
if (menuPrevilges == null)
menuPrevilges = new ArrayList<MenuPrevilege>();
return menuPrevilges;
}
public Menu(String url, String description) {
super();
this.url = url;
this.description = description;
}
}
i'm having this exception org.hibernate.QueryException: could not resolve property:menuPrevilege , and i don't know how to deal with it. this is the MenuPrevilege entity:
#Entity
#Table(name = "Menu_Previlege")
public class MenuPrevilege implements Serializable {
private IdMenuPrevilege idmenuPrevilege = new IdMenuPrevilege();
private Date activationDate;
private Date deactivationDate;
private Menu menu;
private Previlege previlege;
private static final long serialVersionUID = 1L;
public MenuPrevilege() {
super();
}
#EmbeddedId
public IdMenuPrevilege getIdmenuPrevilege() {
return this.idmenuPrevilege;
}
public void setIdmenuPrevilege(IdMenuPrevilege idmenuPrevilege) {
this.idmenuPrevilege = idmenuPrevilege;
}
#Temporal(TemporalType.DATE)
public Date getActivationDate() {
return this.activationDate;
}
public void setActivationDate(Date activationDate) {
this.activationDate = activationDate;
}
#Temporal(TemporalType.DATE)
public Date getDeactivationDate() {
return this.deactivationDate;
}
public void setDeactivationDate(Date deactivationDate) {
this.deactivationDate = deactivationDate;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
#ManyToOne
#JoinColumn(name = "menu_id", insertable = false, updatable = false)
public Menu getMenu() {
return menu;
}
public void setPrevilege(Previlege previlege) {
this.previlege = previlege;
}
#ManyToOne
#JoinColumn(name = "previlege_id", insertable = false, updatable = false)
public Previlege getPrevilege() {
return previlege;
}
public MenuPrevilege(Menu menu, Previlege previlege) {
super();
getIdmenuPrevilege().setIdMenu(menu.getUrl());
getIdmenuPrevilege().setIdPrevilege(previlege.getPrevilegeId());
this.setMenu(menu);
this.setPrevilege(previlege);
menu.getMenuPrevilges().add(this);
previlege.getPrevilegeMenus().add(this);
}
}
I made name refactoring to my code edit my query and everything seems to be working. Here are the changes :
in the named query:
#NamedQuery(name = "getMenusByPrevilegeId", query = "select m from Menu m JOIN
m.previleges p where p.previlege.previlegeId = :p")})
the entity attribute
private List<MenuPrevilege> previleges;
// getters and setters as well
in the constructor of the MenuPrevilege entity
public MenuPrevilege(Menu menu, Previlege previlege) {
super();
getIdmenuPrevilege().setIdMenu(menu.getUrl());
getIdmenuPrevilege().setIdPrevilege(previlege.getPrevilegeId());
this.setMenu(menu);
this.setPrevilege(previlege);
menu.getPrevileges().add(this);
previlege.getMenus().add(this);
}
as u can notice it was a syntax error in my query that caused the exception.

Resources