I'm new with JSF2. and I'm trying to create dynamic h:selectManyListbox using p:dataTable but unfortunately the xhtml page is always blank, Can you help me plz :
This is my xhtml section :
<h:body>
Hi
<p:dataTable id="dataTable" value="#{branchesController.dynamicListBoxBean}" var="item">
Hi Man
#{item.category}
<h:selectManyListbox size="20" style="width: 300px" value="#{item.selectedBranches}" >
<f:selectItems value="#{item.specificBranches}">
</f:selectItems>
</h:selectManyListbox>
</p:dataTable>
</h:body>
This is my Controller Code :
#ManagedBean(name = "branchesController")
#RequestScoped
public class BranchesController implements Serializable {
#EJB
private entities.BranchesFacade ejbFacade;
private List<Branches> items = null;
private List<Branches> selectedItems = null;
private List<DynamicListBoxBean> dynamicListBoxBean = new ArrayList<>();
public BranchesController() {
}
private BranchesFacade getFacade() {
return ejbFacade;
}
public List<Branches> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
public List<DynamicListBoxBean> getDynamicListBoxBean() {
List<Branches> a = new ArrayList<>();
a= getFacade().findAll();
/* a.set(0, new Branches("1","Bib","Small"));
a.set(1, new Branches("2","Bob","Small"));
a.set(2, new Branches("3","jbb","Small"));*/
List<Branches> s = new ArrayList<>();
s = getFacade().findAll();
/* s.set(0, new Branches("1","Bib","Small"));
s.set(1, new Branches("2","Bob","Small"));
s.set(2, new Branches("3","jbb","Small"));*/
DynamicListBoxBean x = new DynamicListBoxBean("Small",0,a,s);
List<DynamicListBoxBean> abc = new ArrayList<DynamicListBoxBean>();
abc.add(0, x);
dynamicListBoxBean = abc;
return dynamicListBoxBean;
}
public void setDynamicListBoxBean(List<DynamicListBoxBean> dynamicListBoxBean) {
this.dynamicListBoxBean = dynamicListBoxBean;
}
#FacesConverter(forClass = Branches.class)
public static class BranchesControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
BranchesController controller = (BranchesController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "branchesController");
return controller.getFacade().find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Branches) {
Branches o = (Branches) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Branches.class.getName()});
return null;
}
}
}
this is my Branches class :
public class Branches implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "ID")
private String id;
#Size(max = 20)
#Column(name = "NAME")
private String name;
#Size(max = 20)
#Column(name = "CATEGORY")
private String category;
public Branches() {
}
public Branches(String id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
And finally this is my DynamicListBoxBean :
public class DynamicListBoxBean {
private String category;
private int cbValue;
private List<Branches> specificBranches;
private List<Branches> selectedBranches;
public DynamicListBoxBean(String category, int cbValue, List<Branches> specificBranches, List<Branches> selectedBranches) {
this.category = category;
this.cbValue = cbValue;
this.specificBranches = specificBranches;
this.selectedBranches = selectedBranches;
}
With gettters and setters ...
Please help me with this. I'm new with JSF 2 ... and Its always giving me a blank page ... What should I do ?
Related
I am doing an exercise on the CRUD operations in a many-to-many relationship having attributes in the relationship table.
I am attaching my entities and I hope you can help me.
The error mentioned above occurs when I go to ask for the list of elements on the zetautente and zetamessaggio tables.
The same error occurs even when I go to ask for a single element of one of the two above mentioned tables ..
#Entity(name = "ZetaMessaggio")
#Table(name="zetamessaggio")
public class ZetaMessaggio implements Serializable {
private static final long serialVersionUID = -2387302703708194311L;
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "zetamessaggio_seq")
#SequenceGenerator(name = "zetamessaggio_seq",sequenceName = "zetamessaggio_seq",allocationSize = 1)
private Long id;
#Column(name = "titolo")
private String titolo;
#Column(name = "testo")
private String testo;
#OneToMany(
mappedBy = "zetaMessaggio",
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JsonManagedReference(value="zetaMessaggio")
private List<ZetaMessaggioUtente> zetaUtente = new ArrayList<ZetaMessaggioUtente>();
public ZetaMessaggio() {
}
public ZetaMessaggio(String titolo, String testo)
{
this.titolo = titolo;
this.testo = testo;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public List<ZetaMessaggioUtente> getZetaUtente() {
return zetaUtente;
}
public void setZetaUtente(List<ZetaMessaggioUtente> zetaUtenti) {
this.zetaUtente = zetaUtenti;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
ZetaMessaggio other = (ZetaMessaggio) o;
return Objects.equals(new Long(this.id), new Long(other.id))
&& Objects.equals(this.titolo, other.titolo)
&& Objects.equals(this.testo, other.testo);
}
#Override
public int hashCode() {
return Objects.hash( new Long(this.id)
, this.testo
, this.titolo
);
}
}
#Entity(name = "ZetaMessaggioUtente")
#Table(name = "zetamessaggioutente")
public class ZetaMessaggioUtente implements Serializable {
private static final long serialVersionUID = 4060038267093084727L;
#EmbeddedId
private ZetaMessaggioUtenteId id;
#Column(name="data")
private String data;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("idMessaggio")
#JoinColumn(name = "idMessaggio")
#JsonBackReference(value = "zetaMessaggio")
private ZetaMessaggio zetaMessaggio;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("idUtente")
#JoinColumn(name = "idUtente")
#JsonBackReference(value = "zetaUtente")
private ZetaUtente zetaUtente;
private ZetaMessaggioUtente() {}
public ZetaMessaggioUtente(ZetaMessaggioUtenteId id)
{
this.id = id;
}
public ZetaMessaggioUtente(ZetaMessaggio messaggio, ZetaUtente utente)
{
this.zetaMessaggio = messaggio;
this.zetaUtente = utente;
this.id = new ZetaMessaggioUtenteId(messaggio.getId(), utente.getId());
}
public ZetaMessaggioUtenteId getId() {
return id;
}
public void setId(ZetaMessaggioUtenteId id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public ZetaMessaggio getZetaMessaggio() {
return zetaMessaggio;
}
public void setZetaMessaggio(ZetaMessaggio zetaMessaggio) {
this.zetaMessaggio = zetaMessaggio;
}
public ZetaUtente getZetaUtente() {
return zetaUtente;
}
public void setZetaUtente(ZetaUtente zetaUtente) {
this.zetaUtente = zetaUtente;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
{
return false;
}
ZetaMessaggioUtente other = (ZetaMessaggioUtente) o;
return Objects.equals(zetaMessaggio, other.zetaMessaggio)
&& Objects.equals(zetaUtente, other.zetaUtente)
;
}
#Override
public int hashCode()
{
return Objects.hash(zetaMessaggio, zetaUtente);
}
}
#Embeddable
public class ZetaMessaggioUtenteId implements Serializable {
private static final long serialVersionUID = -7372159721389421199L;
#Column(name = "idMessaggio")
private Long idMessaggio;
#Column(name = "idUtente")
private Long idUtente;
private ZetaMessaggioUtenteId(){}
public ZetaMessaggioUtenteId(Long idMessaggio,Long idUtente){
setIdMessaggio(idMessaggio);
setIdUtente(idUtente);
}
public Long getIdMessaggio() {
return idMessaggio;
}
public void setIdMessaggio(Long idMessaggio) {
this.idMessaggio = idMessaggio;
}
public Long getIdUtente() {
return idUtente;
}
public void setIdUtente(Long idUtente) {
this.idUtente = idUtente;
}
#Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass())
{
return false;
}
ZetaMessaggioUtenteId other = (ZetaMessaggioUtenteId) o;
return Objects.equals(new Long(this.idMessaggio), new Long(other.idMessaggio)) &&
Objects.equals(new Long(this.idUtente), new Long(other.idUtente))
;
}
#Override
public int hashCode()
{
return Objects.hash( new Long(this.idMessaggio)
, new Long(this.idUtente)
);
}
}
#Entity(name = "ZetaUtenti")
#Table(name = "zetautenti",uniqueConstraints = {#UniqueConstraint(columnNames = {"Id"})})
public class ZetaUtente implements Serializable {
private static final long serialVersionUID = -5338956772143977741L;
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "zetautenti_seq")
#SequenceGenerator(name = "zetautenti_seq",sequenceName = "zetautenti_seq",allocationSize = 1)
private Long id;
#Column(name = "nome")
private String nome;
#Column(name = "cognome")
private String cognome;
#OneToMany(
mappedBy = "zetaUtente",
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JsonManagedReference(value="zetaUtente")
private List<ZetaMessaggioUtente> zetaMessaggio = new ArrayList<ZetaMessaggioUtente>();
public ZetaUtente() {
}
public ZetaUtente(String nome, String cognome)
{
this.nome = nome;
this.cognome = cognome;
}
public Long getId() {
return id;
}
public void setId(Long id) {
id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public List<ZetaMessaggioUtente> getZetaMessaggio() {
return zetaMessaggio;
}
public void setZetaMessaggio(List<ZetaMessaggioUtente> zetaMessaggi) {
this.zetaMessaggio = zetaMessaggi;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
ZetaUtente other = (ZetaUtente) o;
return Objects.equals(new Long(this.id), new Long(other.id))
&& Objects.equals(this.nome, other.nome)
&& Objects.equals(this.cognome, other.cognome);
}
#Override
public int hashCode() {
return Objects.hash( new Long(this.id)
, this.nome
, this.cognome
);
}
}
By default #OneToMany and #ManyToMany relationships are lazy, so you need to handle receiving lazy data.
There are plenty of advices on the internet, it's very strange that you are asking this question, but if very quickly, you have few ways for getting lazy collection:
Antipatterns: OpenSessionInView and enable_lazy_load_no_trans
Most popular way: to use #Transactional annotation (auto attach object to session pool) or manual with start transaction, get collection, close transactional
Similar way: Hibernate.initialize(<get collection method>)
Manual way: use own SQL request with "JOIN FETCH ..."
Alternative way: to use #Fetch(FetchMode.SUBSELECT) (cannot say anything)
Not proper way (but the fastest temporary solution): to use FetchMode.EAGER for collection
Collections are lazily loaded by default, if you are not aware of this thing then you can check the link Lazy loading of collection.
To make your code working you need to add following in OneToMany :
fetch = FetchType.EAGER
I want to pass following format while posting time using postmapping. so how can i write model and controller. I am new in spring boot so pls help me.
{
"request":
{
"name":"siva",
"mobile":"9788761376",
"parent":"1",
"description":"aaaa"
}
}
My model and controller
MODEL:
----------
#Entity
#Table(name = "project_category")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"created_date", "updated_date"},
allowGetters = true)
public class ProjectCategoryModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotBlank
private String name;
private String description;
private String parent;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_date;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_date;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public Date getCreatedDate() {
return created_date;
}
public void setCreatedDate(Date created_date) {
this.created_date = created_date;
}
public Date getUpdatedDate() {
return updated_date;
}
public void setUpdatedDate(Date updated_date) {
this.updated_date = updated_date;
}
Controller:
#PostMapping("/project/category/create")
public ResponseEntity createProjectCategory(#Valid #RequestBody
ProjectCategoryModel projectCategory) {
String respId = "project.category.create";
Object dbResp = projectCategoryRepository.save(projectCategory);
ResponseDataBuilder rb = new ResponseDataBuilder();
HashMap<String, Object> respData = new HashMap<String, Object>();
respData.put("id",projectCategory.getId());
respData.put("responseCode", "OK");
respData.put("message","Project Category Created");
respData.put("apiId","project.category.create");
respData.put("ts", new Date(System.currentTimeMillis()));
HashMap<String, Object> responseObj = rb.getResponseData(respId,
respData);
ProjectCategoryResponse response = new ProjectCategoryResponse();
return response.sendResponse(responseObj);
}
=================================================================
===================================================================
In your model class i.e ProjectCategoryModel declare one custom type like Request
Create one class named as Request like this
public class Request{
private String name;
private String description;
private String parent;
private long mobile;
//getter and setter
}
Declare this type in ProjectCategoryModel :
MODEL:
----------
#Entity
#Table(name = "project_category")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"created_date", "updated_date"},
allowGetters = true)
public class ProjectCategoryModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private Request request;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_date;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_date;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Request getRequest(){
return request;
}
public void setRequest(Request request){
this.request = request;
}
public Date getCreatedDate() {
return created_date;
}
public void setCreatedDate(Date created_date) {
this.created_date = created_date;
}
public Date getUpdatedDate() {
return updated_date;
}
public void setUpdatedDate(Date updated_date) {
this.updated_date = updated_date;
}
I'm creating dynamic h:selectManyListbox(es) using c:forEach but it seems that when I select different options from the h:selectManyListbox, the value corresponding to the selected options doesn't change. Here is my code. Please help I'm new with JSF 2.
This is my xhtml section (#{item.selectedBranches} not updated when options are selected) :
<h:body>
Hi
<h:form id="hehe">
<c:forEach items="#{branchesController.dynamicListBoxBean}" var="item" >
<h3> <h:outputLabel value="#{item.category}"/> </h3>
<h:selectManyListbox size="20" style="width: 300px" value="#{item.selectedBranches}" id="#{item.category}" >
<f:selectItems value="#{item.specificBranches}" >
</f:selectItems>
</h:selectManyListbox>
</c:forEach>
</h:form>
</h:body>
This is my Controller Code :
#ManagedBean(name = "branchesController")
#RequestScoped
public class BranchesController implements Serializable {
#EJB
private entities.BranchesFacade ejbFacade;
private List<Branches> items = null;
private List<Branches> selectedItems = null;
private List<DynamicListBoxBean> dynamicListBoxBean = new ArrayList<>();
public BranchesController() {
}
private BranchesFacade getFacade() {
return ejbFacade;
}
public List<Branches> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
public List<DynamicListBoxBean> getDynamicListBoxBean() {
List<Branches> a = new ArrayList<>();
a= getFacade().findAll();
/* a.set(0, new Branches("1","Bib","Small"));
a.set(1, new Branches("2","Bob","Small"));
a.set(2, new Branches("3","jbb","Small"));*/
List<Branches> s = new ArrayList<>();
s = getFacade().findAll();
/* s.set(0, new Branches("1","Bib","Small"));
s.set(1, new Branches("2","Bob","Small"));
s.set(2, new Branches("3","jbb","Small"));*/
DynamicListBoxBean x = new DynamicListBoxBean("Small",0,a,s);
List<DynamicListBoxBean> abc = new ArrayList<DynamicListBoxBean>();
abc.add(0, x);
dynamicListBoxBean = abc;
return dynamicListBoxBean;
}
public void setDynamicListBoxBean(List<DynamicListBoxBean>
dynamicListBoxBean) {
this.dynamicListBoxBean = dynamicListBoxBean;
}
#FacesConverter(forClass = Branches.class)
public static class BranchesControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent
component, String value) {
if (value == null || value.length() == 0) {
return null;
}
BranchesController controller = (BranchesController)
facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null,
"branchesController");
return controller.getFacade().find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent
component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Branches) {
Branches o = (Branches) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
"object {0} is of type {1}; expected type: {2}", new Object[]{object,
object.getClass().getName(), Branches.class.getName()});
return null;
}
}
}
this is my Branches class :
public class Branches implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "ID")
private String id;
#Size(max = 20)
#Column(name = "NAME")
private String name;
#Size(max = 20)
#Column(name = "CATEGORY")
private String category;
public Branches() {
}
public Branches(String id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
And finally this is my DynamicListBoxBean :
public class DynamicListBoxBean {
private String category;
private int cbValue;
private List<Branches> specificBranches;
private List<Branches> selectedBranches;
public DynamicListBoxBean(String category, int cbValue, List<Branches>
specificBranches, List<Branches> selectedBranches) {
this.category = category;
this.cbValue = cbValue;
this.specificBranches = specificBranches;
this.selectedBranches = selectedBranches;
}
With gettters and setters ...
I really dont understand what's happening.. Shouldn't the item.selectedBranches points to the property in the managedbean ?
Does it exist a way to control the order in which the tables have been created by the persistence provider? I got this mysql 1146 error. I suppose it happens because it try to create an entity that needs for reservation table but it doesn't found it so this cause the following exception. Does exist a way to fix that?
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'volaconnoi_db.reservation' doesn't exist
Error Code: 1146
Call: ALTER TABLE RESERVATION ADD CONSTRAINT FK_RESERVATION_ROUTE_ID_ROUTE FOREIGN KEY (ROUTE_ID_ROUTE) REFERENCES ROUTE (ID_ROUTE)
Query: DataModifyQuery(sql="ALTER TABLE RESERVATION ADD CONSTRAINT FK_RESERVATION_ROUTE_ID_ROUTE FOREIGN KEY (ROUTE_ID_ROUTE) REFERENCES ROUTE (ID_ROUTE)")
This is the USER_CREDENTIAL entity
#Entity
#Table(name = "USER_CREDENTIAL")
#SecondaryTable(name = "CLIENT", pkJoinColumns=#PrimaryKeyJoinColumn(name="USERNAME"))
public class UserCredential implements Serializable
{
private String username;
private String password;
private String email;
private String group_name;
private Date create_date;
private String name;
private String surname;
private String address;
private String city;
private String zip_code;
private String country;
private int fidelity_points;
private List<PhoneNumber> phoneNumbers;
private List<Reservation> reservationsList;
public UserCredential()
{
}
#Id
#Column(name = "USERNAME", nullable = false)
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
#Column(name = "PASSWORD", nullable = false)
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
#Column(name = "EMAIL", nullable = false)
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
#Column(name = "GROUP_NAME", insertable = false, updatable = false)
public String getGroup_name()
{
return group_name;
}
public void setGroup_name(String group_name)
{
this.group_name = group_name;
}
#Column(name = "CREATE_DATE", insertable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getCreate_date()
{
return create_date;
}
public void setCreate_date(Date create_date)
{
this.create_date = create_date;
}
#Column(name = "NAME", nullable= false, table="CLIENT")
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
#Column(name = "SURNAME", nullable= false, table = "CLIENT")
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
#Column(name = "ADDRESS", nullable= false , table = "CLIENT")
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
#Column(name = "CITY", nullable = false, table = "CLIENT")
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
#Column(name = "ZIP_CODE", nullable = false, table = "CLIENT")
public String getZip_code()
{
return zip_code;
}
public void setZip_code(String zip_code)
{
this.zip_code = zip_code;
}
#Column(name = "COUNTRY", nullable = false, table = "CLIENT")
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
#Column(name = "FIDELITY_POINTS", nullable = false, table = "CLIENT")
public int getFidelity_points()
{
return fidelity_points;
}
public void setFidelity_points(int fidelity_points)
{
this.fidelity_points = fidelity_points;
}
#ElementCollection
#CollectionTable(name = "CLIENT_PHONE_NUMBER", joinColumns = #JoinColumn(name = "USERNAME"))
public List<PhoneNumber> getPhoneNumbers()
{
return phoneNumbers;
}
public void setPhoneNumbers (List<PhoneNumber> phoneNumbers)
{
this.phoneNumbers = phoneNumbers;
}
#OneToMany(mappedBy = "username", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public List<Reservation> getReservationsList()
{
return reservationsList;
}
public void setReservationsList(List<Reservation> reservationsList)
{
this.reservationsList = reservationsList;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the username fields are not set
if (!(object instanceof UserCredential))
{
return false;
}
UserCredential other = (UserCredential) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.UserCredential[ id=" + username + " ]";
}
}
THIS IS THE ROUTE ENTITY
#Entity
#Table(name = "ROUTE")
public class Route implements Serializable
{
private String id_route;
private String airlane;
private String aircraft_id;
private Airport airport_city_source;
private Airport airport_city_dest;
private Date departure_date;
private Date arrival_date;
private String travel_class;
private int seats;
private float price;
private List<Reservation> reservationsList;
public Route()
{
}
#PrePersist
public void setIdRoute()
{
SimpleDateFormat sdf = new SimpleDateFormat("ddMMYYYYHHmm");
String format_departure_date = sdf.format(this.getDeparture_date());
String unique_id_route = this.getAirlane() +
this.getAircraft_id() +
this.getAirport_city_source().getCity() +
this.getAirport_city_dest().getCity() +
format_departure_date;
this.setId_route(unique_id_route.replaceAll(" ", ""));
}
#Id
#Column(name = "ID_ROUTE")
public String getId_route()
{
return id_route;
}
public void setId_route(String id_route)
{
this.id_route = id_route;
}
#Column(name = "AIRLANE", nullable = false)
public String getAirlane()
{
return airlane;
}
public void setAirlane(String airlane)
{
this.airlane = airlane;
}
#Column(name = "AIRCRAFT_ID", nullable = false)
public String getAircraft_id()
{
return aircraft_id;
}
public void setAircraft_id(String aircraft_id)
{
this.aircraft_id = aircraft_id;
}
#OneToOne(optional = false)
public Airport getAirport_city_source()
{
return airport_city_source;
}
public void setAirport_city_source(Airport airport_city_source)
{
this.airport_city_source = airport_city_source;
}
#OneToOne(optional = false)
public Airport getAirport_city_dest()
{
return airport_city_dest;
}
public void setAirport_city_dest(Airport airport_city_dest)
{
this.airport_city_dest = airport_city_dest;
}
#Column(name = "DEPARTURE_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getDeparture_date()
{
return this.departure_date;
}
public void setDeparture_date(Date departure_date)
{
this.departure_date = departure_date;
}
#Column(name = "ARRIVAL_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getArrival_date()
{
return arrival_date;
}
public void setArrival_date(Date arrival_date)
{
this.arrival_date = arrival_date;
}
#Column(name = "TRAVEL_CLASS", nullable = false)
public String getTravel_class()
{
return travel_class;
}
public void setTravel_class(String travel_class)
{
this.travel_class = travel_class;
}
#Column(name = "SEATS", nullable = false)
public int getSeats()
{
return seats;
}
public void setSeats(int seats)
{
this.seats = seats;
}
#Column(name = "PRICE", nullable = false)
public float getPrice()
{
return price;
}
public void setPrice(float price)
{
this.price = price;
}
#OneToMany(mappedBy = "route", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public List<Reservation> getReservationsList()
{
return reservationsList;
}
public void setReservationsList(List<Reservation> reservationsList)
{
this.reservationsList = reservationsList;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (id_route != null ? id_route.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id_route fields are not set
if (!(object instanceof Route))
{
return false;
}
Route other = (Route) object;
if ((this.id_route == null && other.id_route != null) || (this.id_route != null && !this.id_route.equals(other.id_route)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.Route[ id=" + id_route + " ]";
}
}
This is the RESERVATION entity
#Entity
#Table(name = "RESERVATION")
public class Reservation implements Serializable
{
private String id;
private int passengers;
private int luggages;
private float price;
private Date date_reservation;
private boolean cancelled;
private UserCredential username;
private Route route;
public Reservation()
{
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_RESERVATION")
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
#Column(name = "PASSENGERS", nullable = false)
public int getPassengers()
{
return passengers;
}
public void setPassengers(int passengers)
{
this.passengers = passengers;
}
#Column(name = "LUGGAGES", nullable = false)
public int getLuggages()
{
return luggages;
}
public void setLuggages(int luggages)
{
this.luggages = luggages;
}
#Column(name = "PRICE", nullable = false)
public float getPrice()
{
return price;
}
public void setPrice(float price)
{
this.price = price;
}
#Column(name = "DATE_PLACED", insertable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getDate_reservation()
{
return date_reservation;
}
public void setDate_reservation(Date date_reservation)
{
this.date_reservation = date_reservation;
}
#Column(name = "CANCELLED", nullable = false)
public boolean isCancelled()
{
return cancelled;
}
public void setCancelled(boolean cancelled)
{
this.cancelled = cancelled;
}
#ManyToOne
#JoinColumn(name = "USERNAME", nullable = false)
public UserCredential getUsername()
{
return username;
}
public void setUsername(UserCredential username)
{
this.username = username;
}
#ManyToOne
#JoinColumn(name = "ID_ROUTE", nullable = false)
public Route getRoute()
{
return route;
}
public void setRoute(Route route)
{
this.route = route;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (id != null ? id.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 Reservation))
{
return false;
}
Reservation other = (Reservation) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.Reservation[ id=" + id + " ]";
}
}
As you may see these three entities are related to each one
I believe this is an error so fixing this may make your problem go away. Then again this may be unrelated:
In Reservation, the type of id is String, but in getId() you specify GenerationType.IDENTITY. AFAIK MySQL doesn't support auto generation of string IDs but only integer IDs. Remove this and see if things work.
UPDATE:
I've reproduced the error on my machine, and this is indeed the problem. If you check your output you will find a warning (not an error) similar to:
[EL Warning]: 2014-06-20
15:47:46.224--ServerSession(1565614310)--Exception [EclipseLink-4002]
(Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5):
org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Incorrect column specifier for column 'ID' Error Code: 1063 Call:
CREATE TABLE NEWENTITY (ID VARCHAR(255) AUTO_INCREMENT NOT NULL, NAME
VARCHAR(255), PRIMARY KEY (ID)) Query: DataModifyQuery(sql="CREATE
TABLE NEWENTITY (ID VARCHAR(255) AUTO_INCREMENT NOT NULL, NAME
VARCHAR(255), PRIMARY KEY (ID))")
I imagine you missed it because it's a warning and not an error. I also imagine this gets output as a warning and not an error because sometimes an error creating the table is not an issue (for example, if the table already exists). EclipseLink apparently isn't smart enough to handle cases where there is a true error, so it outputs as a warning (see "JPA sucks", above).
The EclipseLink/MySQL combination does not support a generation type of IDENTITY for String IDs. IDENTITY means that it's up to the database (and not the JPA implementation provider) to create the ID. MySQL only supports creating integer IDs so the column type must be integer if you use AUTO INCREMENT (see the generated code).
If you really want your IDs to be a String but also automatically generate an ID, then use a generation type of AUTO. AUTO means the JPA implementation provider will handle creating the IDs; EclipseLink will use a sequence table and will handle converting the values there to a String for you.
I have the following (full) entity class.
public class StateTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "state_id", nullable = false)
private Long stateId;
#Column(name = "state_name", length = 45)
private String stateName;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<UserTable> userTableSet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<City> citySet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<Inquiry> inquirySet;
#OneToMany(mappedBy = "shippingState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet;
#OneToMany(mappedBy = "paymentState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet1;
#JoinColumn(name = "country_id", referencedColumnName = "country_id")
#ManyToOne(fetch = FetchType.LAZY)
private Country countryId;
public StateTable() {
}
public StateTable(Long stateId) {
this.stateId = stateId;
}
public Long getStateId() {
return stateId;
}
public void setStateId(Long stateId) {
this.stateId = stateId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
#XmlTransient
public Set<UserTable> getUserTableSet() {
return userTableSet;
}
public void setUserTableSet(Set<UserTable> userTableSet) {
this.userTableSet = userTableSet;
}
#XmlTransient
public Set<City> getCitySet() {
return citySet;
}
public void setCitySet(Set<City> citySet) {
this.citySet = citySet;
}
#XmlTransient
public Set<Inquiry> getInquirySet() {
return inquirySet;
}
public void setInquirySet(Set<Inquiry> inquirySet) {
this.inquirySet = inquirySet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet() {
return orderTableSet;
}
public void setOrderTableSet(Set<OrderTable> orderTableSet) {
this.orderTableSet = orderTableSet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet1() {
return orderTableSet1;
}
public void setOrderTableSet1(Set<OrderTable> orderTableSet1) {
this.orderTableSet1 = orderTableSet1;
}
public Country getCountryId() {
return countryId;
}
public void setCountryId(Country countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (stateId != null ? stateId.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 StateTable)) {
return false;
}
StateTable other = (StateTable) object;
if ((this.stateId == null && other.stateId != null) || (this.stateId != null && !this.stateId.equals(other.stateId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.StateTable[ stateId=" + stateId + " ]";
}
}
I need only two properties from this class as a JSON response namely, stateId and stateName. The rest of the properties must be ignored from being processed/serialized by JSON.
I have tried to set json.excludeProperties to the json interceptor as follows.
#Namespace("/admin_side")
#ResultPath("/WEB-INF/content")
#ParentPackage(value="json-default")
public final class StateListAction extends ActionSupport implements Serializable, ValidationAware
{
#Autowired
private final transient SharableService sharableService=null;
private static final long serialVersionUID = 1L;
private Long id;
List<StateTable>stateTables=new ArrayList<StateTable>();
public StateListAction() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JSON(name="stateTables")
public List<StateTable> getStateTables() {
return stateTables;
}
public void setStateTables(List<StateTable> stateTables) {
this.stateTables = stateTables;
}
#Action(value = "PopulateStateList",
results = {
#Result(type="json", name=ActionSupport.SUCCESS, params={"json.enableSMD", "true", "json.enableGZIP", "true", "json.excludeNullProperties", "true", "json.root", "stateTables", "json.excludeProperties", "userTableSet, citySet, inquirySet, orderTableSet, orderTableSet1, countryId", "validation.validateAnnotatedMethodOnly", "true"})})
public String populateStateList() throws Exception
{
System.out.println("countryId = "+id);
stateTables=sharableService.findStatesByCountryId(id);
return ActionSupport.SUCCESS;
}
}
The remaining properties are expected to be ignored after doing this but it doesn't seem to work. Number of SQL statements associated with all of the entity classes are generated which in turn causes other severe errors to occur like,
org.apache.struts2.json.JSONException: java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public"
What am I missing here? How to ignore all the properties except stateId and stateName?
I'm using Struts2-json-plugin-2.3.16.
You need to configure includeProperties in the json result. For example
#Result(type="json", params = {"contentType", "text/javascript", "includeProperties",
"stateTables\\[\\d+\\]\\.stateId,stateTables\\[\\d+\\]\\.stateName"})