Jpa + Spring Data : cascading of a collection with compound key - java

I'm currently working on a small shop application for my School.
I have 2 objects I want to save :
Order.java
#Entity
#Table(name = "ORDERS")
public class Order {
private Integer id;
private Date orderDate;
private MailingAddress mailingAddress;
private User user;
private Collection<OrderLine> orderLines;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "ORDER_DATE")
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
#ManyToOne
#JoinColumn(name = "SHIPPING_ADR_ID", referencedColumnName = "ID")
public MailingAddress getMailingAddress() {
return mailingAddress;
}
public void setMailingAddress(MailingAddress mailingAddressByShippingAdrId) {
this.mailingAddress = mailingAddressByShippingAdrId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", referencedColumnName = "LOGIN")
public User getUser() {
return user;
}
public void setUser(User userByUserId) {
this.user = userByUserId;
}
#OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Collection<OrderLine> getOrderLines() {
return orderLines;
}
public void setOrderLines(Collection<OrderLine> orderLinesesById) {
this.orderLines = orderLinesesById;
}
}
OrderLine.java
#Entity
#Table(name = "ORDER_LINES", schema = "")
#IdClass(OrderLinesPK.class)
public class OrderLine {
private int quantity;
private Integer orderId;
private String bookId;
private Book book;
private Order order;
#Basic
#Column(name = "QUANTITY")
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Id
#Column(name = "ORDERS_ID", insertable = false, updatable = false)
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer ordersId) {
this.orderId = ordersId;
}
#Id
#Column(name = "BOOKS_ID", insertable = false, updatable = false)
public String getBookId() {
return bookId;
}
public void setBookId(String booksId) {
this.bookId = booksId;
}
#ManyToOne
#JoinColumn(name = "BOOKS_ID", referencedColumnName = "ISBN13", nullable = false, insertable = false, updatable = false)
public Book getBook() {
return book;
}
public void setBook(Book booksByBookId) {
this.book = booksByBookId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ORDERS_ID", referencedColumnName = "ID", nullable = false, insertable = false, updatable = false)
public Order getOrder() {
return order;
}
public void setOrder(Order ordersByOrderId) {
this.order = ordersByOrderId;
}
}
OrderLinesPK.java
public class OrderLinesPK implements Serializable {
private int ordersId;
private String booksId;
#Column(name = "ORDERS_ID")
#Id
public int getOrderId() {
return ordersId;
}
public void setOrderId(int ordersId) {
this.ordersId = ordersId;
}
#Column(name = "BOOKS_ID")
#Id
public String getBookId() {
return booksId;
}
public void setBookId(String booksId) {
this.booksId = booksId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderLinesPK that = (OrderLinesPK) o;
if (ordersId != that.ordersId) return false;
if (booksId != null ? !booksId.equals(that.booksId) : that.booksId != null) return false;
return true;
}
#Override
public int hashCode() {
int result = ordersId;
result = 31 * result + (booksId != null ? booksId.hashCode() : 0);
return result;
}
}
An order contains a collection of order lines.
I'm trying to save the order + the order lines in one call to OrderRepository.
But when I do that, I get the error
org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of edu.flst.bookstore.domaine.bo.OrderLinesPK.orderId
which is pretty logic (I know the Id of the order is unknow at this stage, because the primary key of order is auto-incremented (I use MySQL)).
I don't know how to make this work with one call to orderService (without saving orderLines with orderLinesRepository first). Is it even possible ?
Regards

An Order can contain many Books and a Book can appear in many Order(s). So the many-to-many relation is your OrderLine object essentially. I would set an id (autogenerated) and two many-to-one relations in OrderLine. Then you discard the OrderLinesPK class, you save the Order, Book and OrderLine objects in this order in the same transaction.In this way, your model is simpler and you only need to save an extra id (with no physical meaning) in the database (the id of the OrderLine object)

Related

TableView not showing values when using two Objects JAVAFX with Hibernate

I am trying to create a TableView in JavaFX, but after many attempts values are not showing without giving any Errors.
If i create a TableView with only one Object declared (TableView) it works properly.
I already tried to create a "helper" class, which contained both objects as it's attributes, but still the same problem no errors just TableView not working.
Any suggestions how to fix this?
Here is what i am trying to do:
public TableColumn<CarEntity, String> HistoryBrand;
public TableColumn<CarEntity, String> HistoryColor;
public TableColumn<CarEntity, Date> HistoryDate;
public TableColumn<CarEntity,String> HistoryCategory;
public TableColumn<CarEntity,Double> HistoryPrice;
public TableColumn<OrdersArchiveEntity, Integer> HistoryCarScore;
public TableColumn<OrdersArchiveEntity, Integer> HistoryOrderScore;
public TableColumn<OrdersArchiveEntity, Date> HistoryRentalDate;
public TableColumn<OrdersArchiveEntity, Date> HistoryReturnDate;
public TableView HistoryTable;
HistoryBrand.setCellValueFactory(new PropertyValueFactory<CarEntity, String>("mark"));
HistoryColor.setCellValueFactory(new PropertyValueFactory<CarEntity,String>("color"));
HistoryDate.setCellValueFactory(new PropertyValueFactory<CarEntity, Date>("productionDate"));
HistoryCategory.setCellValueFactory(new PropertyValueFactory<CarEntity, String>("category"));
HistoryPrice.setCellValueFactory(new PropertyValueFactory<CarEntity, Double>("price"));
HistoryCarScore.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Integer>("carScore"));
HistoryOrderScore.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Integer>("orderScore"));
HistoryRentalDate.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Date>("rentalDate"));
HistoryReturnDate.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Date>("returnDate"));
Query queryHist = session.createQuery("select c, o from OrdersArchiveEntity o, CarEntity c where c.id=o.carByCarId.id");
List HistoryList = queryHist.list();
ObservableList Historia = FXCollections.observableArrayList(HistoryList);
HistoryTable.setItems(Historia);
And here are my Classes
package DataBase;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "Car", schema = "dbo", catalog = "master")
public class CarEntity {
private int id;
private RentalBaseEntity RentalBaseEntityByRentalBaseId;
public String mark;
public String color;
public Date productionDate;
public double price;
private String category;
#Id
#Column(name = "ID", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Mark", nullable = false, length = 20)
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
#Basic
#Column(name = "Color", nullable = false, length = 20)
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
#Basic
#Column(name = "Production_Date", nullable = false)
public Date getProductionDate() {
return productionDate;
}
public void setProductionDate(Date productionDate) {
this.productionDate = productionDate;
}
#Basic
#Column(name = "Price", nullable = false, precision = 0)
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
#Basic
#Column(name = "Category", nullable = false, length = 20)
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CarEntity carEntity = (CarEntity) o;
return id == carEntity.id &&
Double.compare(carEntity.price, price) == 0 &&
Objects.equals(mark, carEntity.mark) &&
Objects.equals(color, carEntity.color) &&
Objects.equals(productionDate, carEntity.productionDate) &&
Objects.equals(category, carEntity.category);
}
#Override
public int hashCode() {
return Objects.hash(id, mark, color, productionDate, price, category);
}
#ManyToOne
#JoinColumn(name = "RentalBase_Id", referencedColumnName = "ID", nullable = false)
public RentalBaseEntity getRentalBaseEntityByRentalBaseId() {
return RentalBaseEntityByRentalBaseId;
}
public void setRentalBaseEntityByRentalBaseId(RentalBaseEntity here) {
this.RentalBaseEntityByRentalBaseId = here;
}
}
package DataBase;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "OrdersArchive", schema = "dbo", catalog = "master")
public class OrdersArchiveEntity {
private int id;
private int orderScore;
private int carScore;
private Date rentalDate;
private Date returnDate;
private CarEntity carByCarId;
private SellerEntity sellerBySellerId;
private ClientEntity clientByClientId;
private RentalBaseEntity RentalBaseEntitybyID;
private int Orders_Id;
#Id
#Column(name = "ID", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Order_Score", nullable = false)
public int getOrderScore() {
return orderScore;
}
public void setOrderScore(int orderScore) {
this.orderScore = orderScore;
}
#Basic
#Column(name = "Orders_Id", nullable = false)
public int getOrders_Id() {
return Orders_Id;
}
public void setOrders_Id(int Orders_Id) {
this.Orders_Id = Orders_Id;
}
#Basic
#Column(name = "Car_Score", nullable = false)
public int getCarScore() {
return carScore;
}
public void setCarScore(int carScore) {
this.carScore = carScore;
}
#Basic
#Column(name = "Rental_Date", nullable = false)
public Date getRentalDate() {
return rentalDate;
}
public void setRentalDate(Date rentalDate) {
this.rentalDate = rentalDate;
}
#Basic
#Column(name = "Return_Date", nullable = false)
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersArchiveEntity that = (OrdersArchiveEntity) o;
return id == that.id &&
orderScore == that.orderScore &&
carScore == that.carScore && Objects.equals(rentalDate, that.rentalDate) &&
Objects.equals(returnDate, that.returnDate) ;
}
#Override
public int hashCode() {
return Objects.hash(id, orderScore, carScore, rentalDate, returnDate);
}
#ManyToOne
#JoinColumn(name = "id_Base", referencedColumnName = "ID", nullable = false)
public RentalBaseEntity getRentalBaseEntitybyID() {
return RentalBaseEntitybyID;
}
public void setRentalBaseEntitybyID(RentalBaseEntity RentalBaseEntitybyID) {
this.RentalBaseEntitybyID = RentalBaseEntitybyID;
}
#ManyToOne
#JoinColumn(name = "Car_Id", referencedColumnName = "ID", nullable = false)
public CarEntity getCarByCarId() {
return carByCarId;
}
public void setCarByCarId(CarEntity carByCarId) {
this.carByCarId = carByCarId;
}
#ManyToOne
#JoinColumn(name = "Seller_Id", referencedColumnName = "ID")
public SellerEntity getSellerBySellerId() {
return sellerBySellerId;
}
public void setSellerBySellerId(SellerEntity sellerBySellerId) {
this.sellerBySellerId = sellerBySellerId;
}
#ManyToOne
#JoinColumn(name = "Client_Id", referencedColumnName = "ID", nullable = false)
public ClientEntity getClientByClientId() {
return clientByClientId;
}
public void setClientByClientId(ClientEntity clientByClientId) {
this.clientByClientId = clientByClientId;
}
}

Related entities are null after calling saveAll in Spring JPA

I have these entities
NormalizedChannelStock.java
#Entity
#Table(name = "stocks")
public class NormalizedChannelStock {
#EmbeddedId
private NormalizedChannelStockId id;
#Column(name = "qty")
private int qty;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "channel_id", insertable = false, updatable = false)
private Channel channel;
#Column(name = "created_at", updatable = false)
private Timestamp createdAt;
#Column(name = "updated_at", updatable = false)
private Timestamp updatedAt;
public NormalizedChannelStockId getId() {
return id;
}
public void setId(NormalizedChannelStockId id) {
this.id = id;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public Timestamp getUpdatedAt() {
return updatedAt;
}
}
NormalizedChannelStockId.java
#Embeddable
public class NormalizedChannelStockId implements Serializable {
#Column(name = "channel_id")
private Integer channelId;
#Column(name = "sku")
private String sku;
public NormalizedChannelStockId() {
}
public NormalizedChannelStockId(Integer channelId, String sku) {
this.channelId = channelId;
this.sku = sku;
}
public Integer getChannelId() {
return channelId;
}
public void setChannelId(Integer channelId) {
this.channelId = channelId;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NormalizedChannelStockId that = (NormalizedChannelStockId) o;
return channelId.equals(that.channelId) &&
sku.equals(that.sku);
}
#Override
public int hashCode() {
return Objects.hash(channelId, sku);
}
}
Channel.java
#Entity
#Table(name = "channels")
public class Channel {
#Id
#Column(name = "channel_id")
private int channelId;
#Column(name = "channel_name")
private String channelName;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "store_id", insertable = false, updatable = false)
private Store store;
public int getChannelId() {
return channelId;
}
public void setChannelId(int channelId) {
this.channelId = channelId;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public Store getStore() {
return store;
}
public void setStore(Store store) {
this.store = store;
}
}
The problem I'm facing is when I call
List<NormalizedChannelStock> entitiesToSave = ...
List<NormalizedChannelStock> savedEntities = normalizedChannelStockService.saveAll(entitiesToSave);
The returned entities in savedEntities have their Channel inner objects set to null, as well as their created_at and updated_at as shown
Is this normal behaviour? When I run a findAllById on the Repository, the Channels inside the Entities are loaded lazily properly, so I believe the entities are properly mapped in code. The problem is after I save them.
Does JPA not reload the entity after saving it?
As you stated in the comments you did not set those values before saving.
JPA does not load them for you. JPA pretty much doesn't load anything upon saving except the id if it is generated by the database.
A more common case of the same problem/limitation/misconceptions are bidirectional relationships: JPA pretty much ignores the not owning side and the developer has to make sure that both sides are in sync at all times.
You would have to refresh the entity yourself. Note that just loading it in the same transaction would have no effect because it would come from the 1st level cache and would be exactly the same instance.

Hibernate OneToMany creating many records

I have this two object Input and IndisponibleSegment with a relation one to many respectively:
#Entity
#Table(name= "input")
public class Input {
private long _id;
private String _name;
private Set<IndisponibleSegment> _indisponibleSegments;
#Column(name = "name", unique = true, nullable = false, length = 25)
public String getName() {
return _name;
}
public void setName(String inName) {
this._name = inName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public long getId() {
return _id;
}
public void setId(long inId) {
this._id = inId;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "input", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<IndisponibleSegment> getIndisponibleSegments() {
return _indisponibleSegments;
}
public void setIndisponibleSegments(Set<IndisponibleSegment> inIndisponibleSegments) {
this._indisponibleSegments = inIndisponibleSegments;
}
}
And:
#Entity
#Table(name = "indisponible_segment")
public class IndisponibleSegment {
private Lane _lane;
private int _id;
private Input _input;
#ManyToOne(fetch=FetchType.EAGER)
#Cascade(value={org.hibernate.annotations.CascadeType.ALL})
#JoinColumn(name="input_id")
public Input getInput() {
return _input;
}
public void setInput(Input inInput) {
this._input = inInput;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id")
public int getId() {
return _id;
}
public void setId(int inId) {
this._id = inId;
}
#Enumerated(EnumType.STRING)
#Column(name = "lane", nullable = false)
public Lane getLane() {
return _lane;
}
public void setLane(Lane inLane) {
this._lane = inLane;
}
}
My problem is that everytime run a code like:
DAO dao = new DAO();
Input input = dao.get(Input.class, new Long(1));
if(input==null) {
input = new Input();
input.setName("Input 1");
}
Set<IndisponibleSegment> islist = new HashSet<>();
IndisponibleSegment is = new IndisponibleSegment();
is.setInput(input);
is.setLane(Lane.LANE_FAST);
islist.add(is);
input.setIndisponibleSegments(islist);
dao.saveOrUpdate(input);
I get a new entry in the indisponible_segments table and the old is not removed, thus still there.
I have tried all combinations I can think of: Cascade, delete-orphans, unique constranits... all. What am I doing wrong? All I want is that if I set a new the indisponibleSegments the old ones are deleted.

Composite primary Key and Data truncation error

I'm using Hibernate and MySql and today I setted a composite primary key in one of my table, so below:
DefSelfLearning
And this entity is OneToMany with SelfLearning:
This is my java entity:
#Entity
#Table(name = "defselflearning", catalog = "ats")
public class DefSelfLearning implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
private DefSelfLearningKeys defSelfLearningKeys;
private Ecu ecu;
private String excelColumn;
#JsonIgnore
private Set<SelfLearning> selfLearnings = new HashSet<SelfLearning>(0);
public DefSelfLearning() {
}
public DefSelfLearning(DefSelfLearningKeys defSelfLearningKeys, Ecu ecu) {
this.defSelfLearningKeys = defSelfLearningKeys;
this.ecu = ecu;
}
public DefSelfLearning(Ecu ecu, DefSelfLearningKeys defSelfLearningKeys, String excelColumn, Set<SelfLearning> selfLearnings) {
this.ecu = ecu;
this.defSelfLearningKeys = defSelfLearningKeys;
this.excelColumn = excelColumn;
this.selfLearnings = selfLearnings;
}
#Id
public DefSelfLearningKeys getDefSelfLearningKeys() {
return this.defSelfLearningKeys;
}
public void setDefSelfLearningKeys(DefSelfLearningKeys defSelfLearningKeys) {
this.defSelfLearningKeys = defSelfLearningKeys;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_ecu", nullable = false)
public Ecu getEcu() {
return this.ecu;
}
public void setEcu(Ecu ecu) {
this.ecu = ecu;
}
#Column(name = "excelColumn", length = 2)
public String getExcelColumn() {
return this.excelColumn;
}
public void setExcelColumn(String excelColumn) {
this.excelColumn = excelColumn;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "defSelfLearning")
public Set<SelfLearning> getSelfLearnings() {
return this.selfLearnings;
}
public void setSelfLearnings(Set<SelfLearning> selfLearnings) {
this.selfLearnings = selfLearnings;
}
}
the class for the composite key:
#Embeddable
public class DefSelfLearningKeys implements Serializable {
private static final long serialVersionUID = 1L;
protected String parName;
protected String description;
protected String note;
public DefSelfLearningKeys() {}
public DefSelfLearningKeys(String parName, String description, String note) {
this.parName = parName;
this.description = description;
this.note = note;
}
#Column(name = "parName", nullable = false, length = 15)
public String getParName() {
return this.parName;
}
public void setParName(String parName) {
this.parName = parName;
}
#Column(name = "description", nullable = false, length = 100)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "note", nullable = false, length = 100)
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
}
and SelfLearning class:
#Entity
#Table(name = "selflearning", catalog = "ats")
public class SelfLearning implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idSelfLearning;
private Acquisition acquisition;
private DefSelfLearning defSelfLearning;
private String value;
public SelfLearning() {
}
public SelfLearning(int idSelfLearning, Acquisition acquisition, DefSelfLearning defSelfLearning) {
this.idSelfLearning = idSelfLearning;
this.acquisition = acquisition;
this.defSelfLearning = defSelfLearning;
}
public SelfLearning(int idSelfLearning, Acquisition acquisition, DefSelfLearning defSelfLearning, String value) {
this.idSelfLearning = idSelfLearning;
this.acquisition = acquisition;
this.defSelfLearning = defSelfLearning;
this.value = value;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id_selfLearning", unique = true, nullable = false)
public int getIdSelfLearning() {
return this.idSelfLearning;
}
public void setIdSelfLearning(int idSelfLearning) {
this.idSelfLearning = idSelfLearning;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_acquisition", nullable = false)
public Acquisition getAcquisition() {
return this.acquisition;
}
public void setAcquisition(Acquisition acquisition) {
this.acquisition = acquisition;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "id_parName", nullable = false),
#JoinColumn(name = "id_description", nullable = false),
#JoinColumn(name = "id_note", nullable = false)
})
public DefSelfLearning getDefSelfLearning() {
return this.defSelfLearning;
}
public void setDefSelfLearning(DefSelfLearning defSelfLearning) {
this.defSelfLearning = defSelfLearning;
}
#Column(name = "value")
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
but when I create a defSelfLearning all work fine, but when I create a SelfLearning I receive MysqlDataTruncation exception:
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'id_parName' at row 1
This error is enough explined, but I don't find where is the problem, this is the code for SelfLearning creation:
for (DefSelfLearning defSelfLearning:defSelfLearningList){
SelfLearning selfLearning=new SelfLearning();
String key = defSelfLearning.getExcelColumn()+index;
String value = actualRowValues.get(key);
selfLearning.setAcquisition(findByCarAndExcelRow(carServices.findById(acquisitionForm.getCar()), index));
selfLearning.setDefSelfLearning(defSelfLearning);
selfLearning.setValue(value);
System.out.println(selfLearning.getDefSelfLearning().getDefSelfLearningKeys().getParName());
selfLearningServices.create(selfLearning);
}
Do you find where is the problem?Thanks
This is the first row of defSelfLearning and it's where the code fails
if I set manually this it works:
This is a screen of java debug of first code, that fails:
You try to insert a char which is longer than 15 in the column "id_parName"
On your Entities, you have to choose between field and getter. And all the annotations should be on fields, or they should all be on getters, you can't mix both approaches (except if you use the #AccessType annotation).
Hibernate / Jpa will pick up the used approch from the annotation on Id.
Change #Id on the first Embeddable entity to #EmbeddedId and make sure it is on the getter.
SelfLearning wrong mappings the columns, id_parName= id_description, id_description= id_note and id_note=id_parName, but why?
So I read:
When the JoinColumns annotation is used, both the name and the
referencedColumnName elements must be specified in each such
JoinColumn annotation.
I have added this element so:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "id_parName", referencedColumnName="parName", nullable = false),
#JoinColumn(name = "id_description", referencedColumnName="description", nullable = false),
#JoinColumn(name = "id_note", referencedColumnName="note", nullable = false)
})
public DefSelfLearning getDefSelfLearning() {
return this.defSelfLearning;
}
And it works

CASCADETYPE in EclipseLink JPA

I have two classess. The first class is TNota.
#Entity
#Table(name = "t_nota")
public class TNota implements Serializable {
#Id
#SequenceGenerator(name="seq_t_nota", sequenceName="seq_t_nota", initialValue=37, allocationSize=1)
#GeneratedValue(generator="seq_t_nota")
#Basic(optional = false)
#Column(name = "id_nota", nullable = false)
private double idNota;
#Basic(optional = false)
#Column(name = "nota", nullable = false, length = 255)
private String nota;
#JoinColumn(name = "id_tipo_nota", referencedColumnName = "id", nullable = false)
#ManyToOne(optional = false)
private NTipoNota nTipoNota;
public TNota() {
}
public TNota(Long idNota) {
this.idNota = idNota;
}
public double getIdNota() {
return idNota;
}
public void setIdNota(double idNota) {
this.idNota = idNota;
}
public String getNota() {
return nota;
}
public void setNota(String nota) {
this.nota = nota;
}
public NTipoNota getNTipoNota() {
return nTipoNota;
}
public void setNTipoNota(NTipoNota nTipoNota) {
this.nTipoNota = nTipoNota;
}
}
and the other class is NtipoNota..
#Entity
#Table(name = "n_tipo_nota")
public class NTipoNota implements Serializable {
#Id
#Basic(optional = false)
#Column(name = "id", nullable = false)
private Integer id;
#Basic(optional = false)
#Column(name = "nombre", nullable = false, length = 255)
private String nombre;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "nTipoNota",fetch=FetchType.LAZY)
private List<TNota> tNotaList;
public NTipoNota() {
}
public NTipoNota(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List<TNota> getTNotaList() {
return tNotaList;
}
public void setTNotaList(List<TNota> tNotaList) {
this.tNotaList = tNotaList;
}
}
I have all type of notes stored in database. I just want to persist a new TNota as follows, but I got an error because it persists a new NTipoNota with id= 5 which already exists in database. Using TopLink I never had this trouble:
TNota note = new TNota();
note.setNota("Hola mundo");
note.setNTipoNota(new NTipoNota(5));
manager.persist(note);
I fixed as follow:
TNota note = new TNota();
note.setNota("Hola mundo");
note.setNTipoNota(manager.find(NTipoNota.class, 5);
manager.persist(note);
I would like not to have to change all code due to this problem. Is there any form to make that do not persist the objects when we create a new instance of them?.
Thanks for all.
You new code is correct, and your previous code is not correct. You could also call merge to resolve the relationship.

Categories

Resources