JPA CDI JAXB - Setter getting ignored - java

My JAX-RS Resource is successfully getting a JPA/JAXB entity and a list of JPA/JAXB entities from a db.
One entity serves as a parent entity. The list of entities is a field in the parent entity. I can't set the parent entity's list to the returned list of entities. The parent entity is returned in a JAXB parent entity, but that doesn't affect the situation.
Here's the code:
#Inject
InventoryService inventoryService;
#Inject
HcUser user;
#Inject
InventoryResponse inventoryResponse;
#GET
#Produces(MediaType.APPLICATION_JSON)
public InventoryResponse getInventory(#Context HttpServletRequest request,
#HeaderParam(IDENTITY_URL) String identityURL,
#HeaderParam(ACCESS_TOKEN) String accessToken) {
String username = (String) request.getAttribute("username");
user = inventoryService.getUserById(username);
user.setHcCounts(inventoryService.getCountsForUserId(username));
inventoryResponse.setUser(user);
return inventoryResponse;
}
The returned JSON is only returning the user object. I've tried manually instantiating a user object and setting it to the return value of the getUserById method and then calling setHcCounts with the returned list. However, the setter is still ignored.
What am I doing wrong?
I'm using WAS v8.0.0.8. The stack is:
JAX-RS - Apache Wink v1.1.1 (supplied by WAS 8)
OpenJPA - Apache v2.1.2-SNAPSHOT (supplied by WAS 8)
JAXB - MOXy v2.7
CDI - Apache OpenWebBeans 1.0 (supplied by WAS 8)
EJB - Apache OpenEJB (supplied by WAS 8)
Update 1
Here's the InventoryResponse class as requested, however I don't think that it's necessary. Upon inspecting the user object, on the line before inventoryResonse.setUser(user), during debugging, hcCounts is null.
#Named
#RequestScoped
#XmlRootElement
public class InventoryResponse implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private HcUser user;
private List<HcLocation> locations;
public HcUser getUser() {
return user;
}
public void setUser(HcUser user) {
this.user = user;
}
public List<HcLocation> getLocations() {
return locations;
}
public void setLocations(List<HcLocation> locations) {
this.locations = locations;
}
}
Update 2
As requested, HcUser:
import java.io.Serializable;
import javax.inject.Named;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
import java.util.List;
#Entity
#Table(schema="<ommitted>", name="<ommitted>")
#Named
#XmlRootElement
public class HcUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false, length=100)
private String id;
#Column(nullable=false, length=1)
private boolean active;
#Temporal(TemporalType.DATE)
#Column(name="CREATE_DATE")
private Date createDate;
#Column(name="FIRST_NAME", length=100)
private String firstName;
#Column(name="LAST_NAME", length=100)
private String lastName;
#Temporal(TemporalType.DATE)
#Column(name="UPDATE_DATE")
private Date updateDate;
//bi-directional many-to-one association to HcAssignment
#OneToMany(mappedBy="hcUser")
#XmlElement
private List<HcAssignment> hcAssignments;
//bi-directional many-to-one association to HcCount
#OneToMany(mappedBy="hcUser")
#XmlElement
private List<HcCount> hcCounts;
public HcUser() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public boolean getActive() {
return this.active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getUpdateDate() {
return this.updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public List<HcAssignment> getHcAssignments() {
return this.hcAssignments;
}
public void setHcAssignments(List<HcAssignment> hcAssignments) {
this.hcAssignments = hcAssignments;
}
public HcAssignment addHcAssignment(HcAssignment hcAssignment) {
getHcAssignments().add(hcAssignment);
hcAssignment.setHcUser(this);
return hcAssignment;
}
public HcAssignment removeHcAssignment(HcAssignment hcAssignment) {
getHcAssignments().remove(hcAssignment);
hcAssignment.setHcUser(null);
return hcAssignment;
}
public List<HcCount> getHcCounts() {
return this.hcCounts;
}
public void setHcCounts(List<HcCount> hcCounts) {
this.hcCounts = hcCounts;
}
public HcCount addHcCount(HcCount hcCount) {
getHcCounts().add(hcCount);
hcCount.setHcUser(this);
return hcCount;
}
public HcCount removeHcCount(HcCount hcCount) {
getHcCounts().remove(hcCount);
hcCount.setHcUser(null);
return hcCount;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof HcUser)) {
return false;
}
HcUser other = (HcUser) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
}
Update 3
Here's the code for HcCount:
import java.io.Serializable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
import java.math.BigDecimal;
import java.util.Date;
#Entity
#Table(schema="<omitted>", name="<omitted>")
#Named
#XmlRootElement
public class HcCount implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="HC_COUNT_ID_GENERATOR", sequenceName="COUNT_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="HC_COUNT_ID_GENERATOR")
#Column(unique=true, nullable=false)
private long id;
#Column(name = "LOCATION_NUM", nullable = false, length = 100)
private String locationNum;
#Column(name = "PRODUCT_CODE", nullable = false, length = 100)
private String productCode;
#Column(name = "USER_ID", nullable = false, length = 100)
private String userId;
#Column(name = "LOT_CODE", nullable = false, length = 100)
private String lotCode;
#Column(name="\"COUNT\"")
private BigDecimal count;
#Temporal(TemporalType.DATE)
#Column(name="COUNT_DATE", unique=true, nullable=false)
private Date countDate;
#Temporal(TemporalType.DATE)
#Column(name="CREATE_DATE")
private Date createDate;
#Temporal(TemporalType.DATE)
#Column(name="UPDATE_DATE")
private Date updateDate;
//bi-directional many-to-one association to HcUser
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcUser hcUser;
//bi-directional many-to-one association to HcLocation
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LOCATION_NUM", referencedColumnName="NUM", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcLocation hcLocation;
//bi-directional many-to-one association to HcProduct
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="PRODUCT_CODE", referencedColumnName="CODE_ID", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcProduct hcProduct;
//bi-directional many-to-one association to HcLot
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LOT_CODE", referencedColumnName="CODE_ID", unique=true, nullable=false)
#XmlElement
#XmlInverseReference(mappedBy="hcCounts")
#Inject private HcLot hcLot;
public HcCount() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getLocationNum() {
return locationNum;
}
public void setLocationNum(String locationNum) {
this.locationNum = locationNum;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLotCode() {
return lotCode;
}
public void setLotCode(String lotCode) {
this.lotCode = lotCode;
}
public BigDecimal getCount() {
return this.count;
}
public void setCount(BigDecimal count) {
this.count = count;
}
public Date getCountDate() {
return this.countDate;
}
public void setCountDate(Date countDate) {
this.countDate = countDate;
}
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return this.updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public HcUser getHcUser() {
return this.hcUser;
}
public void setHcUser(HcUser hcUser) {
this.hcUser = hcUser;
}
public HcLocation getHcLocation() {
return this.hcLocation;
}
public void setHcLocation(HcLocation hcLocation) {
this.hcLocation = hcLocation;
}
public HcProduct getHcProduct() {
return this.hcProduct;
}
public void setHcProduct(HcProduct hcProduct) {
this.hcProduct = hcProduct;
}
public HcLot getHcLot() {
return this.hcLot;
}
public void setHcLot(HcLot hcLot) {
this.hcLot = hcLot;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof HcCount)) {
return false;
}
HcCount other = (HcCount) obj;
if (id != other.id) {
return false;
}
return true;
}
}
Update 4
I've figured out a workaround...
public InventoryResponse getInventory(#Context HttpServletRequest request, #HeaderParam(IDENTITY_URL) String identityURL, #HeaderParam(ACCESS_TOKEN) String accessToken) {
String username = (String) request.getAttribute("username");
user = inventoryService.getUserById(username);
List<HcCount> counts = inventoryService.getCountsForUserId(username);
HcUser newUser = new HcUser();
newUser.setHcCounts(counts);
inventoryResponse.setUser(newUser);
return inventoryResponse;
}

Related

org.springframework.orm.jpa.JpaSystemException: Error accessing field by reflection for persistent property

I am using Spring Boot (v 2.4.0) with Hibernate 5.4.24 and, when trying to get some information from my database, I keep getting this error message:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1
It is kind of weird for me, because it only happens when I try to access the table Shoppingcart, since I can get informatin from the rest of the tables.
I also used the exact same entities with another project but, insetad of using Spring Boot, persistence was made with EntityManagers and it worked perfectly fine.
These are my entities:
Shoppingcart
#Entity
#NamedQuery(name="Shoppingcart.findAll", query="SELECT s FROM Shoppingcart s")
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
private int usID;
//bi-directional many-to-many association to Product
#ManyToMany
#JoinTable(
name="sc_has_product"
, joinColumns={
#JoinColumn(name="scID")
}
, inverseJoinColumns={
#JoinColumn(name="productID")
}
)
private List<Product> products;
//bi-directional one-to-one association to User
#OneToOne(mappedBy="shoppingcart")
private User user;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public int getusID() {
return this.usID;
}
public void setusID(int usID) {
this.usID = usID;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isNull() {
return getProducts().isEmpty();
}
User
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String address;
#Column(name="card_n")
private Long cardN;
private String city;
private String country;
private int cvv;
private String email;
private String exp;
private String name;
private String pass;
private String surname1;
private String surname2;
private String typeOfUser;
#Column(name="zip_code")
private int zipCode;
//bi-directional many-to-one association to Order
#OneToMany(mappedBy="user")
private List<Orders> orders;
//bi-directional many-to-one association to Product
#OneToMany(mappedBy="user")
private List<Product> products;
//bi-directional one-to-one association to Shoppingcart
#OneToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="ID", referencedColumnName="usID", insertable=false, updatable=false)
private Shoppingcart shoppingcart;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getCardN() {
return this.cardN;
}
public void setCardN(Long cardN) {
this.cardN = cardN;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCvv() {
return this.cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExp() {
return this.exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSurname1() {
return this.surname1;
}
public void setSurname1(String surname1) {
this.surname1 = surname1;
}
public String getSurname2() {
return this.surname2;
}
public void setSurname2(String surname2) {
this.surname2 = surname2;
}
public int getZipCode() {
return this.zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public List<Orders> getOrders() {
return this.orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Orders addOrder(Orders order) {
getOrders().add(order);
order.setUser(this);
return order;
}
public Orders removeOrder(Orders order) {
getOrders().remove(order);
order.setUser(null);
return order;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product addProduct(Product product) {
getProducts().add(product);
product.setUser(this);
return product;
}
public Product removeProduct(Product product) {
getProducts().remove(product);
product.setUser(null);
return product;
}
public Shoppingcart getShoppingcart() {
return this.shoppingcart;
}
public void setShoppingcart(Shoppingcart shoppingcart) {
this.shoppingcart = shoppingcart;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
}
This is the ShoppingcartDAO class:
public interface ShoppingCartDAO extends CrudRepository<Shoppingcart, Integer> {
#Query("SELECT s FROM Shoppingcart s JOIN User u ON u.id = s.usID AND u.id LIKE :id")
Shoppingcart findByUser(#Param("id") int id);
#Query("SELECT s FROM Shoppingcart s")
List<Shoppingcart> findAllShoppingCart();
}
And, finally, this is my ShoppingcartController class:
#RestController
#CrossOrigin
#EnableAutoConfiguration
public class ShoppingCartController {
#Autowired
ShoppingCartDAO scDAO;
#RequestMapping(value = "sc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> assignShoppingCart(#RequestBody(required = true) Shoppingcart sc) {
try {
scDAO.save(sc);
return new ResponseEntity<Void>(HttpStatus.CREATED);
} catch(Exception e) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
#RequestMapping(value = "sc", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getEveryShoppingCart() {
try {
List<Shoppingcart> sc = scDAO.findAllShoppingCart();
return new ResponseEntity<List<Shoppingcart>>(sc, (sc != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
} catch(Exception e) {
System.out.println(e);
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
}
I am really going nuts as I canĀ“t figure out what is going on with my code, so thank you in advance if you help me.
I finally fixed it. For those of you who are wondering how, I deleted the relationships between tables that I had, ending with:
Shoppingcart:
#Entity
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
#Column(name = "usID")
private Integer userID;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
Product:
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int productID;
private String category;
private String color;
private String description;
private String estadoProducto;
private String fecha;
private int orderID;
private String photo;
private double price;
private int seller;
private String sexo;
private String state = "Disponible";
private String talla;
private String title;
public Product() {
}
public int getProductID() {
return this.productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEstadoProducto() {
return this.estadoProducto;
}
public void setEstadoProducto(String estadoProducto) {
this.estadoProducto = estadoProducto;
}
public String getFecha() {
return this.fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTalla() {
return this.talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public int getSeller() {
return seller;
}
public void setSeller(int seller) {
this.seller = seller;
}
With this, everything worked fine, but don't ask me why, because I don't know it.
Your Getters/Setters are wrongly implemented.
Like :
Actual :
public int getusID() {
return this.usID;
}
Expected :
public int getUsID() {
return this.usID;
}
Same with setter

Foreign key always Null in DB

I got this error in Spring: enter image description here When I try to join two table entities.
And the foreign key is always Null in DB, Why?
My Entity Classes - Task, ListeExecJob.
Please, help me
Task :
#SuppressWarnings("serial")
#Entity
#Table(name ="task")
public class Task implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "nom_job", length = 20,nullable = false)
private String nom_job;
#Column(name = "type_commande", length = 20,nullable = false)
private String type_commande;
#Column(name = "description", length = 100, nullable = false)
private String description;
#Column(name = "script", length = 100, nullable = false)
private String script;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "date_execution")
private Date date_execution;
#Column(name = "active")
private boolean active;
#ManyToOne
#JoinColumn(name="id_liste")
private ListeExecJob liste;
public ListeExecJob getListe() {
return liste;
}
public void setListe(ListeExecJob liste) {
this.liste = liste;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNom_job() {
return nom_job;
}
public void setNom_job(String nom_job) {
this.nom_job = nom_job;
}
public String getType_commande() {
return type_commande;
}
public void setType_commande(String type_commande) {
this.type_commande = type_commande;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public boolean getActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Task() {
}
public Task(Integer id, String nom_job, String type_commande, String description, String script,
Date date_execution, boolean active) {
super();
this.id=id;
this.nom_job = nom_job;
this.type_commande = type_commande;
this.description = description;
this.script = script;
this.date_execution = date_execution;
this.active=active ;
}
}
ListeExecJob.java
____________________________________________________
#SuppressWarnings("serial")
#Entity
#Table(name ="liste")
#JsonIgnoreProperties(
value = {"dateCreation"},
allowGetters = true
)
public class ListeExecJob implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idListe")
private int idListe;
#Column(name = "status")
private String status;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "date_creation")
#CreatedDate
private Date date_creation;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#JoinColumn(name = "date_execution")
private Date date_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "fin_execution")
private Date fin_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "next_execution")
private Date next_execution;
#OneToMany(mappedBy="liste",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JsonIgnore
private List<Task> task;
public int getIdListe() {
return idListe;
}
public void setIdListe(int idListe) {
this.idListe = idListe;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public Date getFin_execution() {
return fin_execution;
}
public void setFin_execution(Date fin_execution) {
this.fin_execution = fin_execution;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonIgnore
public List<Task> getTask() {
if (task == null) {
task = new ArrayList<>();
}
return this.task;
}
public void addTask(Task task) {
getTask().add((Task) task);
((Task) task).setListe(this);
}
public void removeTask(Task task) {
getTask().remove(task);
task.setListe(null);
}
#JsonSetter
public void setTask(List<Task> task) {
this.task = task;
}
public ListeExecJob() {
}
public ListeExecJob(int idListe, String status, Date date_creation, Date date_execution, Date b
fin_execution,
Date next_execution) {
super();
this.idListe = idListe;
this.status = status;
this.date_creation = date_creation;
this.date_execution = date_execution;
this.fin_execution = fin_execution;
this.next_execution = next_execution;
}
}
Task service
#Service
#Transactional(propagation= Propagation.SUPPORTS)
#Primary
public class TaskService {
#Autowired
private TaskRepository repository;
#Autowired
private ListeExecJobService service;
#Autowired
public TaskService(TaskRepository repository) {
super();
this.repository = repository;
}
public List<Task> listAllTask(){
return repository.findAll();
}
public Task addTask(Task task){
ListeExecJob ab = service.getByreferenece(task.getListe().getIdListe());
ab.addTask(task);
return repository.save(task);
/* task.setListe(ab);
System.out.println(task.getListe().getIdListe());
ab.addTask(task);*/
}
public Task updateTask(Integer id , Task task){
Task job1 = new Task();
job1 = task;
job1.setId(id);
return addTask(job1);
}
public void deleteTask(Integer id){
repository.deleteById(id);
}
public Task getByreferenece(Integer id){
return repository.findById(id).isPresent()? repository.findById(id).get():null;
}
}
ListeExecJobService
#Service
#Transactional
#Primary
public class ListeExecJobService {
#Autowired
private ListeExecJobRepository SJIRepos;
#Autowired
public ListeExecJobService(ListeExecJobRepository SJIRepos) {
super();
this.SJIRepos = SJIRepos;
}
public List<ListeExecJob> listAllListeExecJob(){
return SJIRepos.findAll();
}
public ListeExecJob addListeExecJob(ListeExecJob SJI){
return SJIRepos.save(SJI);
}
public ListeExecJob getByreferenece(Integer idListe){
return SJIRepos.findById(idListe).isPresent()? SJIRepos.findById(idListe).get():null;
}
public void deleteListeExecJob(Integer idListe){
SJIRepos.deleteById(idListe);
}
public ListeExecJob updateListeExecJob(Integer idListe , ListeExecJob sji){
ListeExecJob sji01 = new ListeExecJob();
sji01 = sji;
sji01.setIdListe(idListe);
return addListeExecJob(sji01);
}
public void deleteById(Integer idListe) {
SJIRepos.deleteById(idListe);
}
}
try #JoinColumn(name="id_liste",referencedColumnName = "idListe") in the task class, you have a problem in the join column

Cannot remove object list in java spring

my code is :
List<Session> futureSessions = this.getFutureSession(group.getSessions());
for (Session session: futureSessions) {
Boolean exists = false;
for (SessionDTO sessionDTO: groupDTO.getSessions()) {
if (session.getId() == sessionDTO.getId()) {
exists = true;
}
}
if(false == exists) {
// sessionService.delete(session);
group.getSessions().remove(session);
} else {
exists = false;
}
} Group groupUpdated = groupService.save(group);
This part of code is for remove object (session) into my group object. I use java spring for dilog between angular and java.
I have a relationship between this 2 objects and before save my group object i look for if my session groupServive.save(group) my sessions are not removed from database.
Any help will be very appreciate !
Here is my group model :
`#Entity
#Table(name = "t_group")
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Boolean actif;
private Boolean deleted;
private Enterprise enterprise;
private String avatar;
private Date date_creation;
private Date date_update;
private Integer version;
private Set<User> users;
private List<Rule> rules;
private List<Session> sessions;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(nullable = false, unique = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(nullable = false)
public Boolean getActif() {
return actif;
}
public void setActif(Boolean actif) {
this.actif = actif;
}
#Column(nullable = false)
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#ManyToOne
#JoinColumn(name = "t_enterprise", nullable = true)
public Enterprise getEnterprise() {
return enterprise;
}
public void setEnterprise(Enterprise enterprise) {
this.enterprise = enterprise;
}
#Lob
#Column(columnDefinition = "LONGTEXT")
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_update() {
return date_update;
}
public void setDate_update(Date date_update) {
this.date_update = date_update;
}
#ManyToMany
#JoinTable(name = "t_user_group", joinColumns = {
#JoinColumn(name = "t_group", nullable = false) },
inverseJoinColumns = { #JoinColumn(name = "t_user") })
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="group")
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="group")
public List<Session> getSessions() {
return sessions;
}
public void setSessions(List<Session> sessions) {
this.sessions = sessions;
}
#Version
#Column(nullable = false)
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#PreUpdate
private void setLastUpdate() {
this.setDate_update(new Date());
}
#PrePersist
private void setFirstCreationDate() {
this.setLastUpdate();
if(null == this.getDate_creation()){
this.setDate_creation(new Date());
}
}
`
ok, the solution was only to add a method in my sessionDAO
`
#Override
public void delete(Session session) {
// repository.delete(session);
if (session.getId() > 0) {
query = em.createNativeQuery("DELETE FROM `t_session` WHERE `id` = :t_session", Session.class);
query.setParameter("t_session", session.getId());
query.executeUpdate();
}
}`

JPA cannot fill entries in join table

I'm trying to map a bidirectional ManyToMany relationship between the class Problem and the class Domain. Therefore the persistency unit creates a join table in the database, but it seems no entry pops up in the database.
Here's some code:
The class Problem
package domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement
public class Problem implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private User user;
private String description;
private int maxprice;
private int priority;
private Solution solution;
private Location location;
private List<Domain> domains;
#Id
//#GeneratedValue(strategy = GenerationType.AUTO)
#SequenceGenerator(name="User_Seq", allocationSize=25)
#GeneratedValue(strategy=SEQUENCE, generator="Problem_Seq")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne
//#JoinColumn(name="user_id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMaxPrice() {
return maxprice;
}
public void setMaxPrice(int maxprice) {
this.maxprice = maxprice;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="solution_id")
public Solution getSolution() {
return solution;
}
public void setSolution(Solution solution) {
this.solution = solution;
}
#ManyToOne
#JoinColumn(name="location_id")
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
#ManyToMany
#JoinTable(name="problem_domain",
joinColumns={#JoinColumn(name="problem_id", referencedColumnName="ID")},
inverseJoinColumns={#JoinColumn(name="domain_id", referencedColumnName="ID")})
public List<Domain> getDomains() {
return domains;
}
public void setDomains(List<Domain> domains) {
this.domains = domains;
}
public void addDomain(Domain domain){
//this.domains.add(domain); //Throws NullpointerException om een of andere reden.
}
#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 Problem)) {
return false;
}
Problem other = (Problem) 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 "domain.Problem[ id=" + id + " ]";
}
}
The class Domain
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement
public class Domain implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private List<Problem> problems;
private List<Domain> subDomains;
private Domain superDomain;
#Id
#SequenceGenerator(name="Dom_Seq", allocationSize=25)
#GeneratedValue(strategy=SEQUENCE, generator="Dom_Seq")
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;
}
#ManyToMany(mappedBy = "domains")
public List<Problem> getProblems() {
return problems;
}
public void setProblems(List<Problem> problems) {
this.problems = problems;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="superdomain_id")
public List<Domain> getSubDomains() {
return subDomains;
}
public void setSubDomains(List<Domain> subDomains) {
this.subDomains = subDomains;
}
public Domain getSuperDomain() {
return superDomain;
}
public void setSuperDomain(Domain superDomain) {
this.superDomain = superDomain;
}
#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 Domain)) {
return false;
}
Domain other = (Domain) 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 "domain.Domain[ id=" + id + " ]";
}
}
the code where we add a problem and a domain to the database
Problem problem = new Problem();
Domain domain = new Domain();
domain.setName(domainString);
domainFacade.create(domain);
problemFacade.create(problem);
problem.addDomain(domain);
problemFacade.edit(problem);
and a little visual explanation of the DB
Do you try to save List of domain to problem?
Example of code:
Problem problem = new Problem();
Domain domain = new Domain();
domain.setName(domainString);
domainFacade.create(domain);
List<Domain> domains = new ArrayList<Domain>();
domains.add(domain);
problem.setDomains(domains);
problemFacade.create(problem);
As #Neil Stockton and others said, the answer to my problem was that I had to have an addMethod that simply added the object to the list.

JPA persist ManyToMany with association class?

I'm trying to persist a relationship #ManyToMany. I created an association class using #IdClass for association, but doesn't work using persist, works only using merge.
I need add others registers but using merge doesn't work because the register is always updated.
I want my table in the database looks like this
id_aluno | id_graduacao | grau | date
1 1 FIRST 2014-08-02
1 1 SECOND 2014-08-02
1 1 THIRD 2014-08-02
My entities
#Entity
#Table(name="aluno")
public class Aluno implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
//historico de graduacao
#OneToMany(mappedBy = "aluno")
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Aluno(){}
/** adiciona lista de HistoricoDeGraduacao para aluno */
public void addListaHistoricoGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
///gets e sets
#Entity
#Table(name="graduacao")
public class Graduacao implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graus_graduacao", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="graus")
private List<String> graus;
#OneToMany(mappedBy = "graduacao")
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Graduacao() {
}
/** adiciona historicodegraduacao a graduacao */
public void addHistoricoDeGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
//gets e sets
public class HistoricoDeGraduacaoId implements Serializable {
private static final long serialVersionUID = 1L;
private Aluno aluno;
private Graduacao graduacao;
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Graduacao getGraduacao() {
return graduacao;
}
public void setGraduacao(Graduacao graduacao) {
this.graduacao = graduacao;
}
#Entity
#IdClass(HistoricoDeGraduacaoId.class)
public class HistoricoDeGraduacao implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "id_aluno")
private Aluno aluno;
#Id
#ManyToOne
#JoinColumn(name="id_graduacao")
private Graduacao graduacao;
private String grau;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
public HistoricoDeGraduacao() {
}
//gets e sets
//persisting
public void insert(){
//doesn't work using persist, works only with merge but record is always updated and not added
em.getTransaction().begin();
Aluno a = new Aluno();
a.setId(1); //aluno have Id
Graduacao g = new Graduacao();
g.setId(1); //graduacao have Id
HistoricoDeGraduacao hdg1 = new HistoricoDeGraduacao();
hdg1.setAluno(a);
hdg1.setGraduacao(g);
hdg1.setDataGraduou(new Date());
hdg1.setGrau("FIRST");
a.addHistoricoDeGraduacao(hdg1);
g.addHistoricoDeGraduacao(hdg1);
em.persist(hdg1);
em.getTransaction().commit();
HistoricoDeGraduacao hdg2 = new HistoricoDeGraduacao();
hdg2.setAluno(a);
hdg2.setGraduacao(g);
hdg2.setDataGraduou(new Date());
hdg2.setGrau("SECOND");
a.addHistoricoDeGraduacao(hdg2);
g.addHistoricoDeGraduacao(hdg2);
em.persist(hdg2);
em.getTransaction().commit();
HistoricoDeGraduacao hdg3 = new HistoricoDeGraduacao();
hdg3.setAluno(a);
hdg3.setGraduacao(g);
hdg3.setDataGraduou(new Date());
hdg3.setGrau("THIRD");
a.addHistoricoDeGraduacao(hdg3);
g.addHistoricoDeGraduacao(hdg3);
em.persist(hdg3);
em.getTransaction().commit();
em.close();
}
Any idea ?
now works
here how I did
#Entity
#Table(name="aluno")
public class Aluno implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
//historico de graduacao
#OneToMany(mappedBy = "aluno", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Aluno() {
}
public void addListaHistoricoGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
public void setListaHistoricoGraduacao(List<HistoricoDeGraduacao> listaHistoricoGraduacao) {
this.listaHistoricoGraduacao = listaHistoricoGraduacao;
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Aluno other = (Aluno) obj;
return true;
}
}
#Entity
#Table(name="graduacao")
public class Graduacao implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graus_graduacao", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="graus")
private List<String> graus;
#OneToMany(mappedBy = "graduacao", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Graduacao() {
}
public Graduacao(Integer id, String graduacao, List<String> graus) {
this.id = id;
this.graduacao = graduacao;
this.graus = graus;
}
/** adiciona historicodegraduacao a graduacao */
public void addHistoricoDeGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGraduacao() {
return graduacao;
}
public void setGraduacao(String graduacao) {
this.graduacao = graduacao;
}
public List<String> getGraus() {
return graus;
}
public void setGraus(List<String> graus) {
this.graus = graus;
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
public void setListaHistoricoGraduacao(List<HistoricoDeGraduacao> listaHistoricoGraduacao) {
this.listaHistoricoGraduacao = listaHistoricoGraduacao;
}
public String toString(){
return graduacao;
}
}
#Embeddable
public class HistoricoDeGraduacaoId implements Serializable {
private static final long serialVersionUID = 1L;
#JoinColumn(name="EMP_ID")
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of generated methods, choose Tools | Templates.
}
#Override
public int hashCode() {
return super.hashCode(); //To change body of generated methods, choose Tools | Templates.
}
}
#Entity
public class HistoricoDeGraduacao implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
HistoricoDeGraduacaoId pk;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_aluno")
private Aluno aluno;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="id_graduacao")
private Graduacao graduacao;
private String grau;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
public HistoricoDeGraduacao() {
}
public void begin(){
//instancia pk
pk = new HistoricoDeGraduacaoId();
//aqui insiro o id
pk.setId(new HistoricoDeGraduacaoDAO().getIndex());
}
public HistoricoDeGraduacaoId getPk() {
return pk;
}
public void setPk(HistoricoDeGraduacaoId pk) {
this.pk = pk;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Graduacao getGraduacao() {
return graduacao;
}
public void setGraduacao(Graduacao graduacao) {
this.graduacao = graduacao;
}
public String getGrau() {
return grau;
}
public void setGrau(String grau) {
this.grau = grau;
}
public Date getDataGraduou() {
return dataGraduou;
}
public void setDataGraduou(Date dataGraduou) {
this.dataGraduou = dataGraduou;
}
#Override
public int hashCode() {
int hash = 3;
hash = 59 * hash + Objects.hashCode(this.aluno);
hash = 59 * hash + Objects.hashCode(this.graduacao);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final HistoricoDeGraduacao other = (HistoricoDeGraduacao) obj;
if (!Objects.equals(this.aluno, other.aluno)) {
return false;
}
if (!Objects.equals(this.graduacao, other.graduacao)) {
return false;
}
return true;
}
}
//aqui meu jframe com seus componentes, pegando valores montando tudo para ser salvo
historico.setDataGraduou(jdp_dataGraduou.getDate());
historico.setGrau(jl_graus.getSelectedValue().toString());
//pega graduacao do jcombobox
Graduacao g = (Graduacao)cbx_graduacao.getSelectedItem();
historico.setGraduacao(g);
//bean aluno
historico.setAluno(bean);
//add a listas
bean.addListaHistoricoGraduacao(historico);
g.addHistoricoDeGraduacao(historico);
//inicia instancia de pk e insere o proximo id
historico.begin();
//salva tudo
new HistoricoDeGraduacaoDAO().update(historico);
//aqui meu DAO
public class HistoricoDeGraduacaoDAO {
private EntityManager em;
public HistoricoDeGraduacaoDAO(){
em = Persistencia.getEntityManager();
}
/** pega o ultimo valor da tabela HistoricoDeGraduacao e adiciona + 1 para o proximo indice */
public Integer getIndex(){
int count = 0;
Query query = em.createQuery("SELECT MAX(hdg.pk.id) FROM HistoricoDeGraduacao hdg");
if(query.getSingleResult() == null){
++count;
}else{
count = (int)query.getSingleResult() + 1;
}
return count;
}
/** executa update */
public void update(HistoricoDeGraduacao historico){
try{
em.getTransaction().begin();
em.merge(historico);
em.getTransaction().commit();
}catch(PersistenceException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}finally{
em.close();
}
}
}

Categories