I have 3 entities (Medecin , Patient , Rendezvous)
Medecin with Idmed , Patient with Idpat are foreign key with ManyToOne relationship in Rendezvous.
When I add a Medecin or a Patient via a form , the Data is perfectly stored .
But when I try to add a Rendezvous , using a Form with two , struts2 select tag , <:select../> who are populated with the list of Id of Patient and Medecin .
Nothing happen.
I have a return success , but the Data is not stored .
How to fix that ?
My form, Rendezvous.jsp
<div class="col-md-4">
<div class="form_main">
<h4 class="heading"><strong>Planifier un </strong> Rendezvous <span></span></h4>
<div class="form">
<s:form action="Ajoutrdv" id="Ajoutrdv" namepace="/pages" theme="bootstrap" cssClass="bs-example form-horizontal">
<s:textfield label="Id du Rendezvous" type="Number" min="1" required="" placeholder="Entrer l'ID du RDV" name="idrdv"/>
<s:select label="Id du Patient" headerKey="-1" headerValue="" list="%{Patient}" listKey="idpat" name="idpat" required="" onchange="getData(this.value)"/>
<s:select label="Id du Medecin" headerKey="-1" headerValue="" list="%{Medecin}" listKey="idmed" name="idmed" required="" onchange="getData(this.value)"/>
<s:textfield type="Date" required="" name="date"></s:textfield>
<s:textfield type="Time" required="" name="heure"></s:textfield>
<s:textarea label="Motif" required="" name="motif"></s:textarea>
<caption><s:submit cssClass="btn btn-primary" value="Enregistrer"/></caption>
</s:form>
</div>
My action in struts2.xml
<package name="Ajoutrdv" namespace="/pages" extends="struts-default">
<action name="Ajoutrdv" class="controller.FormRDVAction" method="Ajoutrdv">
<result name="success">/pages/accueil.jsp</result>
<result name="input">/pages/Rendezvous.jsp</result>
</action>
</package>
FormRDVAction
public class FormRDVAction extends ActionSupport {
private Integer idrdv;
private Medecin idmed;
private Patient idpat;
private String date;
private String heure;
private String motif;
private List<Rendezvous> Rendezvous;
// getters setters
// Add action
public String Ajoutrdv() {
RendezvousDAO rdvDAO= RendezvousDAO.getInstance();
Rendezvous R = new Rendezvous();
R.setIdmed(idmed);
R.setIdpat(idpat);
R.setIdrdv(idrdv);
R.setDate(date);
R.setHeure(heure);
R.setMotif(motif);
rdvDAO.saveRendezvous(R);
return SUCCESS;
}
}
RendezvousDAO
public void saveRendezvous(Rendezvous Rendezvous) {
log.info("********** Debut saveRendezvous RendezvousDAO **********");
Session session = SessionFactoryUtil.getInstance().openSession();
Transaction trans = session.beginTransaction();
try {
session.save(Rendezvous);
if (!trans.wasCommitted()) {
trans.commit();
}
} catch (Exception e) {
e.printStackTrace();
log.fatal(e.getMessage());
trans.rollback();
} finally {
session.close();
}
}
Finally , mapping class Rendezvous.java
#Entity
#Table(name = "rendezvous")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Rendezvous.findAll", query = "SELECT r FROM Rendezvous r"),
#NamedQuery(name = "Rendezvous.findByIdrdv", query = "SELECT r FROM Rendezvous r WHERE r.idrdv = :idrdv"),
#NamedQuery(name = "Rendezvous.findByDate", query = "SELECT r FROM Rendezvous r WHERE r.date = :date"),
#NamedQuery(name = "Rendezvous.findByHeure", query = "SELECT r FROM Rendezvous r WHERE r.heure = :heure"),
#NamedQuery(name = "Rendezvous.findByMotif", query = "SELECT r FROM Rendezvous r WHERE r.motif = :motif")})
public class Rendezvous implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "idrdv")
private Integer idrdv;
#Basic(optional = false)
#Column(name = "date")
private String date;
#Basic(optional = false)
#Column(name = "heure")
private String heure;
#Basic(optional = false)
#Column(name = "motif")
private String motif;
#JoinColumn(name = "idpat", referencedColumnName = "idpat")
#ManyToOne(optional = false , fetch = FetchType.LAZY)
private Patient idpat;
#JoinColumn(name = "idmed", referencedColumnName = "idmed")
#ManyToOne(optional = false , fetch = FetchType.LAZY)
private Medecin idmed;
public Rendezvous() {
}
public Rendezvous(Integer idrdv) {
this.idrdv = idrdv;
}
public Rendezvous(Integer idrdv, String date, String heure, String motif) {
this.idrdv = idrdv;
this.date = date;
this.heure = heure;
this.motif = motif;
}
public Integer getIdrdv() {
return idrdv;
}
public void setIdrdv(Integer idrdv) {
this.idrdv = idrdv;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getHeure() {
return heure;
}
public void setHeure(String heure) {
this.heure = heure;
}
public String getMotif() {
return motif;
}
public void setMotif(String motif) {
this.motif = motif;
}
public Patient getIdpat() {
return idpat;
}
public void setIdpat(Patient idpat) {
this.idpat = idpat;
}
public Medecin getIdmed() {
return idmed;
}
public void setIdmed(Medecin idmed) {
this.idmed = idmed;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idrdv != null ? idrdv.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 Rendezvous)) {
return false;
}
Rendezvous other = (Rendezvous) object;
if ((this.idrdv == null && other.idrdv != null) || (this.idrdv != null && !this.idrdv.equals(other.idrdv))) {
return false;
}
return true;
}
#Override
public String toString() {
return "mapping.Rendezvous[ idrdv=" + idrdv + " ]";
}
}
Related
So, my entire project seems to work for now. It is a simple system that holds records of all products of a shop. When a new product is made, a barcode will be generated. Now, this works, but I wanted to see my barcode(I can see the longblob in my db) in the output to be sure. I am probably doing it wrong, but I cannot get the image displayed.
The controller and html pages are quit irrelevant for now cause I just made them to see if I would see the barcode, but I don't. So what html tags do I need to use to get this barcode image displayed? I got the barcode object from here:
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
I will display the code from the html, controller and the object. You can find the entire project on git. https://github.com/Muschke/scruplesAntwerpenTwee.
html:
<html lang="nl" xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments::head(title='Index', css=#{/css/css.css})"></head>
<th:block th:if="${producten}">
<table>
<thead>
<th>Gebruiker</th>
<th>Consignatiebon</th>
<th>Eigenschap</th>
<th>Kleur</th>
<th>Merk</th>
<th>Maat</th>
<th>Soort</th>
<th>Barcode</th>
<th>Beschrijving</th>
<th>aankoopprijs</th>
<th>verkoopprijs</th>
<th>status</th>
<th>gestolen</th>
<th>solden</th>
</thead>
<tbody>
<tr th:each="product:${producten}" th:object="${product}">
<td th:text="*{getGebruiker().getNaam()}"></td>
<td th:text="*{getConsignatiebon().getidConsignatiebon()}"></td>
<td th:text="*{getEigenschap().getSubEigenschap()}"></td>
<td th:text="*{getKleur().getKleur()}"></td>
<td th:text="*{getMerk().getNaam()}"></td>
<td th:text="*{getMaat().getNaam()}"></td>
<td th:text="*{getSoort()}"></td>
<td>
<img class='img-thumbnail' th:src="'data:image/jpeg;base64,' + ${imgUtil.getImgData(product.getBarcode())}" />
</td>
<td th:text="*{getBeschrijving()}"></td>
<td th:text="*{getAankoopprijs()}"></td>
<td th:text="*{getVerkoopprijs()}"></td>
<td th:text="*{getStatus()}"></td>
<td th:text="*{getGestolen()}"></td>
<td th:text="*{getSolden()}"></td>
</tr>
</tbody>
</table>
<form th:action="#{/verwerken}" method="post">
<button name="barcodebutton">Genereer barcode</button>
</form>
</th:block>
</html>
controller:
#Controller
#RequestMapping("/")
class IndexController {
private final ProductService productService;
public IndexController(ProductService productService) {
this.productService = productService;
}
#GetMapping
public ModelAndView findAllProducts() {
return new ModelAndView("index").addObject("producten", productService.findAllProducts());
}
#PostMapping("/verwerken")
public ModelAndView barcodeToevoegen() {
var idnu = 52L;
productService.genereerBarcode(idnu);
return new ModelAndView("redirect:/");
}
}
object:
#Table(name = "producten")
public class Product {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private long productId;
#ManyToOne(fetch = FetchType.LAZY, optional = false) #JoinColumn(name = "gebruikerId")
private Gebruiker gebruiker;
#ManyToOne(fetch = FetchType.LAZY, optional = false) #JoinColumn(name = "consignatiebonId")
private Consignatiebon consignatiebon;
#OneToOne #JoinColumn(name = "eigenschapId")
private Eigenschap eigenschap;
#OneToOne #JoinColumn(name = "kleurId")
private Kleur kleur;
#OneToOne #JoinColumn(name = "merkId")
private Merk merk;
#OneToOne #JoinColumn(name = "maatId")
private Maat maat;
#Enumerated(EnumType.STRING)
private Soort soort;
private Barcode barcode;
/*de barcode mag null zijn bij input?, na input van alles, invoke methode creeër barcode.
* dat MOET dan na create worden uitgevoerd in transactional*/
private String beschrijving;
private BigDecimal aankoopprijs;
#Enumerated(EnumType.STRING)
private Status status;
private boolean gestolen;
private boolean solden;
public Product(Gebruiker gebruiker, Consignatiebon consignatiebon, Eigenschap eigenschap, Kleur kleur, Merk merk, Maat maat, Soort soort, Barcode barcode,
String beschrijving, BigDecimal aankoopprijs, Status status,boolean gestolen, boolean solden) {
this.gebruiker = gebruiker;
this.consignatiebon = consignatiebon;
this.eigenschap = eigenschap;
this.kleur = kleur;
this.merk = merk;
this.maat = maat;
this.soort = soort;
this.barcode = barcode;
this.beschrijving = beschrijving;
this.aankoopprijs = aankoopprijs;
this.status = status;
this.gestolen = gestolen;
this.solden = solden;
}
protected Product() {};
public Consignatiebon getConsignatiebon() {
return consignatiebon;
}
public Gebruiker getGebruiker() {
return gebruiker;
}
public long getProductId() {
return productId;
}
public Eigenschap getEigenschap() {
return eigenschap;
}
public Kleur getKleur() {
return kleur;
}
public Merk getMerk() {
return merk;
}
public Maat getMaat() {
return maat;
}
public Soort getSoort() {
return soort;
}
public Barcode getBarcode() {
return barcode;
}
public String getBeschrijving() {
return beschrijving;
}
public BigDecimal getAankoopprijs() {
return aankoopprijs;
}
public BigDecimal getVerkoopprijs() {
return aankoopprijs.multiply(BigDecimal.valueOf(2.5));
}
public Status getStatus() {
return status;
}
public boolean getGestolen() {
return gestolen;
}
public boolean getSolden() {
return solden;
}
/*setters voor vkp en gestolen, en voor elke OTO*/
public void setEigenschap(Eigenschap eigenschap) {
this.eigenschap = eigenschap;
}
public void setKleur(Kleur kleur) {
this.kleur = kleur;
}
public void setMerk(Merk merk) {
this.merk = merk;
}
public void setMaat(Maat maat) {
this.maat = maat;
}
public void setGestolen(boolean gestolen) {
this.gestolen = gestolen;
}
/*equals en hashtagcode maken*/
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product)) return false;
Product product = (Product) o;
return Objects.equals(eigenschap, product.eigenschap) && Objects.equals(kleur, product.kleur) && Objects.equals(merk, product.merk) && Objects.equals(maat, product.maat) && soort == product.soort && Objects.equals(beschrijving, product.beschrijving) && Objects.equals(aankoopprijs, product.aankoopprijs);
}
#Override
public int hashCode() {
return Objects.hash(eigenschap, kleur, merk, maat, soort, beschrijving, aankoopprijs);
}
/*methode om barcode te genereren als er nog geen barcode is:
* we steken het id erin, laten aanvullen met nullen tot aan 12 getallen, 13e wordt automatisch gemaakt*/
//eventueel via #þostload automatisch laten invullen
public void generateAndSetEAN13BarcodeImage() throws Exception {
if(barcode != null) {
throw new IllegalArgumentException();
} else {
var lengte = String.valueOf(getProductId()).length();
StringBuilder langeId = new StringBuilder(String.valueOf(productId));
if (lengte < 12) {
var verschil = 12 - lengte;
for (int i = 0; i < verschil; i++) {
langeId.append(0);
}
}
barcode = BarcodeFactory.createEAN13(String.valueOf(langeId));
}
}
}
So, question again: how can I make the barcode be displayed on the html page?
I have drop-down of Entity "BusinessPartner".
I have all my entities ID's as String and customized "org.hibernate.id.UUIDGenerator" to add relavent prefix to my ID's ex: "BPID_04a3e35b-12b3-447f-a982-338739e537f1"
i am getting the following exception when i try to navigate to the page which contain the drop-down of "BusinessPartner" entity.
Searched all over the internet for solution, let me know if anyone have any clue. I have pointed out where exactly i am getting exception in below snippet.
Java Version: 1.8
Spring Boot Version: 1.5.10.RELEASE
Entity Order:
#Entity
#Table(name = Order.TABLE_NAME)
public class Order extends Model implements Serializable {
#Enumerated(EnumType.STRING)
#Column(name = DOCUMENT_TYPE)
private DocumentType documentType;
#Column(name = DOCUMENT_NUMBER, updatable = false)
private String documentNumber;
#Column(name = ORDER_DESCRIPTION)
#NotEmpty
private String orderDescription;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = COL_OTHER_PARTY_ID, nullable = false)
private BusinessPartner otherParty;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = COL_AUTHORITY_BUSINESS_PARTNER_ID, nullable = false)
private BusinessPartner authority;
}
Entity BusinessPartner:
#Entity
#Table(name = BusinessPartner.ENTITY_NAME)
public class BusinessPartner extends Model {
#Column(name = NAME)
private String name;
#Column(name = EMAIL)
private String email;
// Getters and Setters omitted for simplicity
}
Parent Entity:
#MappedSuperclass
public class Model {
public static final String ID = "id";
public static final String CREATED_AT = "createdAt";
public static final String UPDATED_AT = "updatedAt";
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "com.emisha.database.Generators.IDGenerator")
#Column(name = ID)
private String id;
#Version
private Long version;
#Column(name = CREATED_AT)
private Date createdAt;
#Column(name = UPDATED_AT)
private Date updatedAt;
public Model() {
// Empty Constructor
}
/* DEFINED METHODS */
#PrePersist
protected void onCreate() {
updatedAt = createdAt = new Date();
}
#PreUpdate
protected void onUpdates() {
updatedAt = new Date();
}
// GETTERS & SETTERS
}
Controller method that populates businessPartners:
#Controller
#Secured(SecurityUtil.MANAGE_PURCHASEORDER)
#SessionAttributes("order")
#RequestMapping("Orders")
public class OrderController extends EmishaAdminBaseController {
//.........
#RequestMapping(value = "/{documentType}/form/{id}", method = RequestMethod.GET)
public String getOrder(#PathVariable("documentType") String documentType, #PathVariable("id") String id, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
String view = "PurchaseOrder/form";
if (documentType.equalsIgnoreCase("SalesOrder")) {
view = "SalesOrder/form";
}
User user = Objects.requireNonNull(getCurrentUser()).getUser();
// Mapped Product Data
Order order;
// Default Form control data
String action = request.getContextPath() + "/Orders/" + documentType + "/form/" + id;
String mode = "EDIT_ORDER";
logger.debug("Default mode set to: " + mode + "\n" + "Default action set to: " + action);
if (documentType.equalsIgnoreCase("CreateSalesOrder")) {
action = request.getContextPath() + "/Orders/SalesOrder/form/" + id;
view = "SalesOrder/form";
if (id != null && !id.isEmpty()) {
Order purchaseOrder = orderService.getOrder(id);
order = OrderHelper.convertToSalesOrder(purchaseOrder);
} else {
redirectAttributes.addFlashAttribute("error", "Invalid Purchase Order.");
return "redirect:/Sales/Quotations";
}
} else {
if (id.equals("new")) {
mode = "CREATE_ORDER";
// Create new instance for creating new Procurement Requisition.
order = new Order();
if (documentType.toLowerCase().equals("PurchaseOrder".toLowerCase())) {
// Set default statuses for new Procurement Requisition
order.setStatus(Status.DRAFT);
order.setPublicationType(PublicationType.RESTRICTED);
// Set document type to Purchase Requirement.
order.setDocumentType(DocumentType.PURCHASE_ORDER);
// Set initial processing status to PR Created.
order.setProcessingStatus(ProcessingStatus.PO_CREATED);
} else if (documentType.toLowerCase().equals("SalesOrder".toLowerCase())) {
// Set default statuses for new RFQ ProcurementRequisition
order.setStatus(Status.DRAFT);
order.setPublicationType(PublicationType.RESTRICTED);
// Set document type to Request for Quotation.
order.setDocumentType(DocumentType.SALES_ORDER);
// Set initial processing status to REF Created.
order.setProcessingStatus(ProcessingStatus.SO_CREATED);
}
logger.debug("Mode set to: " + mode + "\n" + "Action set to: " + action);
} else {
order = orderService.getOrder(id);
}
}
addAllDropDowns(model, user);
// Add business data to model
model.addAttribute("order", order);
// Add form control data to model
model.addAttribute("action", action);
model.addAttribute("mode", mode);
return view;
}
//.........
private void addAllDropDowns(Model model, User user) {
// Add dropdown data to model
/* Products drop down */
List<Product> products = new ArrayList<>();
products = productService.getProducts(user.getBusinessPartner());
model.addAttribute("products", products);
/* Unit of Measurements drop down */
List<UnitOfMeasurement> unitOfMeasurements = new ArrayList<>();
unitOfMeasurements = unitOfMeasurementService.getAllUnitOfMeasurements();
model.addAttribute("unitOfMeasurements", unitOfMeasurements);
/* Users drop down */
List<User> users = new ArrayList<>();
users = userService.getUsersWhere(user.getBusinessPartner());
model.addAttribute("users", users);
/* Vendors drop down */
List<BusinessPartner> vendors = new ArrayList<>();
vendors = businessPartnerService.getVendors(user.getBusinessPartner());
model.addAttribute("vendors", vendors);
}
}
Thyemeleaf Drop-down in my view.html file:
<label>Customer</label>
<select th:if="*{order?.quotation ==null}" class="form-control"
th:field="*{otherParty}"
data-placeholder="Select an option" data-allow-clear="true"
tabindex="-1"
style="width: 250px; background-color: #d2e1f3;">
<option value="">Select</option>
<option th:each="vendor,istat : ${vendors}"
th:value="${vendor?.id}" //<---- java.lang.NumberFormatException: For input string: "BPID_04a3e35b-12b3-447f-a982-338739e537f1"
th:text="${vendor?.name}">
Manufacturer
</option>
</select>
Here is the Stack trace:
java.lang.NumberFormatException: For input string: "BPID_04a3e35b-12b3-447f-a982-338739e537f1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_152]
at java.lang.Integer.parseInt(Integer.java:580) ~[na:1.8.0_152]
at java.lang.Integer.valueOf(Integer.java:766) ~[na:1.8.0_152]
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:208) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]...
Hi I am new to Spring Mvc i have 3 tables first is role,resources,roleresource tables respectively. I have a created a jsp in which a list of resources are shown along with check boxes and also rolename where user enters,my prob is i need to insert rolename to role table and generated roleid to roleresource table with selected resources ids. problem here is i am not able to bind selected checkbox values here is my controller
package com.steadyground.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.steadyground.constants.URLConstants;
import com.steadyground.entity.Organization;
import com.steadyground.entity.Resources;
import com.steadyground.form.RoleResourceForm;
import com.steadyground.service.ResourcesService;
#Controller
public class RoleResoucesMappingController {
#Autowired
private ResourcesService resourcesService;
#RequestMapping(value = URLConstants.ROLERESOURCEMAPPING_PAGE, method = RequestMethod.GET)
public String landRoleResourceMapping(ModelMap map)
{
map.addAttribute("roleResourceForm",new RoleResourceForm());
return "roleResourcesMapping";
}
#RequestMapping(value = URLConstants.ROLERESOURCEMAPPING_ADD, method = RequestMethod.POST)
public String createRoleResourceMapping(#ModelAttribute(value="roleResourceForm") RoleResourceForm roleResourceForm, BindingResult result, ModelMap map)
{
System.out.println(roleResourceForm.getResources());
System.out.println(roleResourceForm.getResources().size());
//System.out.println(roleResourceForm.getRole().getRoleResources());
return "roleResourcesMapping";
}
#ModelAttribute("resources")
public List<Resources> getAllResources() {
List<Resources> listResources = new ArrayList<Resources>();
listResources = resourcesService.getAllResources();
return listResources;
}
}
here is my role.java file
#Entity
#Table(name = "role", catalog = "steadyground")
public class Role implements java.io.Serializable {
private Integer roleId;
private String roleName;
private Set<RoleResource> roleResources = new HashSet<RoleResource>(0);
public Role() {
}
public Role(String roleName) {
this.roleName = roleName;
}
public Role(String roleName, String applicationName,
Set<RoleResource> roleResources) {
this.roleName = roleName;
this.roleResources = roleResources;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "role_id", unique = true, nullable = false)
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
#Column(name = "role_name", nullable = false, length = 100)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "role")
public Set<RoleResource> getRoleResources() {
return this.roleResources;
}
public void setRoleResources(Set<RoleResource> roleResources) {
this.roleResources = roleResources;
}
}
here is my resources.java
#Entity
#Table(name = "resources", catalog = "steadyground")
public class Resources implements java.io.Serializable {
private Integer resourceId;
private String url;
private String urlName;
public Resources() {
}
public Resources(String url, String urlName) {
this.url = url;
this.urlName = urlName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "resource_id", unique = true, nullable = false)
public Integer getResourceId() {
return this.resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
#Column(name = "url", length = 100)
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
#Column(name = "url_name", length = 200)
public String getUrlName() {
return this.urlName;
}
public void setUrlName(String urlName) {
this.urlName = urlName;
}
}
here is my roleresource.java
#Entity
#Table(name="role_resource"
,catalog="steadyground"
)
public class RoleResource implements java.io.Serializable {
private Integer roleResourceId;
private Role role;
private Integer resourceId;
public RoleResource() {
}
public RoleResource(Role role, Integer resourceId) {
this.role = role;
this.resourceId = resourceId;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="role_resource_id", unique=true, nullable=false)
public Integer getRoleResourceId() {
return this.roleResourceId;
}
public void setRoleResourceId(Integer roleResourceId) {
this.roleResourceId = roleResourceId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="role_id")
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#Column(name="resource_id")
public Integer getResourceId() {
return this.resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
}
and my jsp page
<springform:form method="post" action="createRoleResourcesMapping" class="form-horizontal" commandName="roleResourceForm" >
<div class="span12">
<div class="center">
<div class="control-group span6">
<label class="control-label" for="Role_Id">Role Id</label>
<div class="control-group span6">
<label class="control-label" for="url_Name">Role Name</label>
<div class="controls">
<div class="span12">
<springform:input path="role.roleName"/>
</div>
</div>
</div>
<div class="page-header position-relative"></div>
<table id="sample-table-2" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Resources</th>
</tr>
</thead>
<tbody>
<tr>
<td><springform:checkboxes path="resources" items="${resources}" itemLabel="urlName" itemValue="resourceId"/>
</td></tr></tbody>
</table>
<div class="controls">
<div class="span12">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="button" class="btn " value="Cancel">
</div>
</div>
</div>
</div>
</springform:form>
could someone help me in how to receive the data and save it in two tables
<springform:checkboxes path="resources" items="${resources}" itemLabel="urlName" itemValue="resourceId"/>
From your code, what I've understood, the RoleResourcesForm is more like a wrapper of the 2 entities Resource & Role with another object resources.
I think, to use form:checkboxes you better give it an object List in the path.
And what's this variable resources?
If it's really an List object in the RoleResourcesForm wrapper, in the items, you should use
items="${roleResourceForm.resources}"
When you commit it, it will send the form model attribute with only checked checkbox values.
My class Categorie needs to have multiple Products, i need to show the products when you click on a category in the jsp... I tried it like this:
#Entity
public class Categorie {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int categorieId;
private String categorieName;
#OneToMany()
#JoinColumn(name = "CategorieNr")
private Set<Product> products;
My Product class:
#Entity
#Table(name = "CentricProduct")
public class Product implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
private int calories, productRow;
private String description;
private double price;
#Override
public boolean equals(Object object) {
if (!(object instanceof Product)) {
return false;
}
Product other = (Product) object;
return description.equals(other.description);
}
#Override
public int hashCode() {
return description.hashCode();
}
This is the repository i use to get the categorys with their products:
#Repository
public class CategoryRepository implements ICategoryRepository
{
#PersistenceContext
private EntityManager em;
public CategoryRepository() {
}
public CategoryRepository(EntityManager em)
{
this.em = em;
}
public void setEntityManager(EntityManager e)
{
this.em = e;
}
#Transactional(readOnly = true)
#Override
public List<Categorie> findAll()
{
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Categorie.class));
return em.createQuery(cq).getResultList();
}
in my jsp:
<h1 class="listtitle">Productenlijst</h1>
<div id="leftlist" class="list" >
<c:forEach items="${products}" var="item" >
<form:form method="POST" action="shoppinglist.htm" modelAttribute="products">
<input type="submit" value= "${item.categorieName}" class="productlistbtn" alt="Submit" input path="${item}" >
</form:form>
</c:forEach>
</div>
your class Product needs to be declared as #Entity. (you can't embed a one-to-many relationship, especially because you're Productcontains it's own ID)
I have a problem regarding jpa query.
There are two tables i.e. Post table and Tag table
There is many to many relationship between Post and Tag
Now I want to write a query such that when multiple tags are chosen then all the posts associated with those tags should be selected.
For example,
post1 has tags friends and motivation
post2 has tags motivation and pune
post3 has tag boxing
if tags friends and pune are chosen then post1 and post 2 should be retrieved
if tag boxing is chosen then only post 3 should be retrieved
if tags boxing and motivation are chosen then all three posts should be retrieved.
I tried following things
SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags IN :tags
but it gives validator error that
The state field path 'p.tags' cannot be resolved to a collection type.
If I try like this
SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags = :tags
then it complies fine but after passing a list of tags it gives error
java.lang.IllegalArgumentException: You have attempted to set a value of type class java.util.ArrayList for parameter tags with expected type of class com.justme.model.entities.Tag from query string SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags = :tags.
Thank you for reading this much :) can you please guide me on this?
how can I achieve the results mentioned above?
my persistence provider is eclipseLink
This is Post entity
#Entity
#NamedQueries({
#NamedQuery(name = "Post.selectAllPosts", query = "SELECT p FROM Post p ORDER BY p.dateCreated DESC"),
#NamedQuery(name = "Post.selectPostForUser", query = "SELECT p FROM Post p WHERE p.user = :user ORDER BY p.dateCreated DESC"),
#NamedQuery(name = "Post.selectPostsByTags", query = "SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags IN :tags") })
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idpost;
#Lob
private String content;
private String title;
// bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "iduser")
private User user;
// bi-directional many-to-many association to Tag
#ManyToMany(cascade = CascadeType.PERSIST)
#JoinTable(name = "post_tag", joinColumns = #JoinColumn(name = "idpost"), inverseJoinColumns = #JoinColumn(name = "idtag"))
private List<Tag> tags = new ArrayList<Tag>();
#Temporal(TemporalType.DATE)
private Date date = null;
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreated = new Date();
public Post() {
}
public int getIdpost() {
return this.idpost;
}
public void setIdpost(int idpost) {
this.idpost = idpost;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public List<Tag> getTags() {
return this.tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Override
public String toString() {
return "Post [idpost=" + idpost + ", content=" + content + ", title="
+ title + ", date=" + date + "]";
}
}
This is Tag Entity
#Entity
#NamedQueries({
#NamedQuery(name = "Tag.selectTags", query = "SELECT tag FROM Tag tag WHERE tag.tagName LIKE :keyword"),
#NamedQuery(name = "Tag.selectMatchingTags", query = "SELECT t.tagName FROM Tag t WHERE t.tagName LIKE :keyword"),
#NamedQuery(name = "Tag.selectTagByName", query = "SELECT tag FROM Tag tag WHERE tag.tagName = :tagName"),
#NamedQuery(name = "Tag.selectTagsForAllPosts", query = "SELECT DISTINCT tag FROM Tag tag, Post post JOIN tag.posts posts WHERE post.user = :user")})
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idtag;
private String tagName;
// bi-directional many-to-many association to Post
#ManyToMany(mappedBy = "tags", cascade = CascadeType.PERSIST)
private List<Post> posts;
public Tag() {
}
public Tag(String tagName) {
this.tagName = tagName;
}
public int getIdtag() {
return this.idtag;
}
public void setIdtag(int idtag) {
this.idtag = idtag;
}
public String getTagName() {
return this.tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public List<Post> getPosts() {
return this.posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
#Override
public String toString() {
return tagName;
}
}
Try:
...
#NamedQuery(name = "Post.selectPostsByTags", query =
"SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE tags IN (:tags)") })
public class Post implements Serializable {
...
Use it like this:
#PersistenceContext
public EntityManager em;
...
List<Tag> ltags = new ArrayList<Tag>();
ltags.add(tagOne);
ltags.add(tagTwo);
List<?> list = em.createNamedQuery("Post.selectPostsByTags")
.setParameter("tags", ltags)
.getResultList();
for (Object object : list) {
System.out.println("Results: "+object);
}