I have a 1 to 1 relation of Moneda and Remesa, but when I go to delete a Moneda or a Remesa, neither deletes me, I don't get any error, simply that they are not deleted in the database. The other relationships in my tables are working fine. I don't know if it's because I have something wrong with the #OneToOne relationship
Moneda.java
#Id
#SequenceGenerator(name = "moneda_sequence", sequenceName = "moneda_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "moneda_sequence")
#Column(name = "ID")
#JsonProperty("id")
private Long id;
#Column(name = "FECHA_INSERCION")
#JsonProperty("fechaInsercion")
#JsonDeserialize(using = JsonDateDeserializer.class)
#JsonSerialize(using = JsonDateSerializer.class)
private LocalDateTime fechaInsercion;
#Column(name = "FECHA_MODIFICACION")
#JsonProperty("fechaModificacion")
#JsonDeserialize(using = JsonDateDeserializer.class)
#JsonSerialize(using = JsonDateSerializer.class)
private LocalDateTime fechaModificacion;
#Column(name = "NOMBRE")
#JsonProperty("nombre")
private String nombre;
#Column(name = "ABREVIATURA")
#JsonProperty("abreviatura")
private String abreviatura;
#OneToOne
#JoinColumn(name = "pais", nullable = true)
#JsonProperty("pais")
private Pais pais;
#OneToMany(mappedBy = "moneda", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
private Set<Corresponsable> corresponsables;
#OneToMany(mappedBy = "moneda", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
private Set<Documento> documentos;
#OneToOne(mappedBy = "moneda", cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
private Remesa remesa;
Remesa.java
#Id
#SequenceGenerator(name = "remesa_sequence", sequenceName = "remesa_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "remesa_sequence")
#Column(name = "ID")
private Long id;
#Column(name = "FECHA_INSERCION")
#JsonDeserialize(using = JsonDateDeserializer.class)
#JsonSerialize(using = JsonDateSerializer.class)
private LocalDateTime fechaInsercion;
#Column(name = "FECHA_MODIFICACION")
#JsonDeserialize(using = JsonDateDeserializer.class)
#JsonSerialize(using = JsonDateSerializer.class)
private LocalDateTime fechaModificacion;
private Integer tipoDoc;
private Integer entidad;
private Integer oficina;
private Integer referencia;
#OneToMany(mappedBy = "remesa", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
private Set<Documento> documento;
#OneToOne(mappedBy = "remesa", cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
private EnvioRemesa envio_id;
#OneToOne
#JoinColumn (name = "moneda_id", nullable = true)
private Moneda moneda;
My method to remove monedas:
public void getDeleteMoneda (Long moneda_id) {
try {
Moneda m = monedaRepo.findById(moneda_id).orElseThrow (() -> new Exception ("bad"));
if (m! = null) {
monedaRepo.deleteById (moneda_id); // HERE RETURN NULL DEBUGGING BUT THERE IS A MONEDA WITH THAT ID
}
} catch (Exception e) {
e.printStackTrace ();
}
}
The same thing happens with Remesa, the method is practically identical. Could it be a problem with the relationship of both tables?
Related
I have the following class:
public class Nomenclature extends BaseEntity {
#Id
#Column(name = "NOMENCLATURE_CODE")
private String nomenclatureCode;
#OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, mappedBy = "nomenclatureCode", orphanRemoval = true)
private List<Cumul> cumuls = new ArrayList<>();
}
I want to join the following Cumul class on 2 columns WHERE cumul.nomenclatureCode = nomenclature.nomenclatureCode OR cumul.nomenclatureCodeAllowedCumul = nomenclature.nomenclatureCode
public class Cumul extends BaseEntity {
#Id
#Column(columnDefinition = "NUMERIC")
#GeneratedValue(generator = "CUMUL", strategy = GenerationType.SEQUENCE)
private Long id;
#Column(name = "NOMENCLATURE_CODE")
private String nomenclatureCode;
#Column(name = "NOMENCLATURE_CODE_ALLOWED_CUMUL")
private String nomenclatureCodeAllowedCumul;
#OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL},orphanRemoval = true)
#JoinColumns(
{
#JoinColumn(name = "nomenclature_code", referencedColumnName = "nomenclature_code"),
#JoinColumn(name = "nomenclature_code_allowed_cumul", referencedColumnName = "nomenclature_code")
})
private List<Cumul> cumuls = new ArrayList<>();
Worked but this an AND statement not an OR what I was looking for
I have next classes:
#Entity
#Table
public class Lesson implements ModelEntity {
#Id
#Column(name = "lesson_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "course_id")
private Course course;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "lesson_type_id")
private LessonType lessonType;
private LocalDate date;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "time_slot_id")
private TimeSlot timeSlot;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "auditorium_id")
private Auditorium auditorium;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "lesson_teacher", joinColumns = #JoinColumn(name = "lesson_id"), inverseJoinColumns = #JoinColumn(name = "person_id"))
private Set<Teacher> teachers = new HashSet<>();;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "lesson_group", joinColumns = #JoinColumn(name = "lesson_id"), inverseJoinColumns = #JoinColumn(name = "group_id"))
private Set<Group> groups = new HashSet<>();
}
#Entity
#Table(name = "groups")
public class Group implements ModelEntity {
#Id
#Column(name = "group_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "group_name")
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "faculty_id")
private Faculty faculty;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group")
private List<Student> students;
}
#Entity
#Table
public class TimeSlot implements ModelEntity {
#Id
#Column(name = "time_slot_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "time_slot_number")
private Integer number;
#Column(name = "time_slot_name")
private String name;
#Column(name = "time_slot_start")
private LocalTime startTime;
#Column(name = "time_slot_end")
private LocalTime endTime;
}
I wrote method, that find all Groups_id by Date and TimeSlot_id not connected to Lesson with CriteriaBuilder API, it works perfect:
#Override
public Set<Integer> getBusyGroupsId(int lessonId, LocalDate date, int timeSlotId) {
logger.debug("getBusyGroupsId() with agruments {}, {}, {}.", lessonId, date, timeSlotId);
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Integer> query = criteriaBuilder.createQuery(Integer.class);
Root<Lesson> root = query.from(Lesson.class);
List<Predicate> predicates = new ArrayList<>();
Join<Lesson, TimeSlot> timeSlotJoin = root.join("timeSlot", JoinType.LEFT);
predicates.add(criteriaBuilder.equal(timeSlotJoin.get("id"), timeSlotId));
predicates.add(criteriaBuilder.equal(root.get("date"), date));
if (nonNull(lessonId)) {
predicates.add(criteriaBuilder.notEqual(root.get("id"), lessonId));
}
query.where(predicates.toArray(new Predicate[] {}));
SetJoin<Lesson, Group> joinGroup = root.joinSet("groups");
query.multiselect(joinGroup.get("id"));
TypedQuery<Integer> result = entityManager.createQuery(query);
return result.getResultStream().collect(Collectors.toSet());
}
But after that I think- what about JPA, can it be easier?
I tried something like that, but it doesnt work:
public Set<Integer> findGroupIdByIdNotAndDateEqualsAndTimeSlotIdEquals(Integer lessonId, LocalDate date, Integer timeSlotId);
How to fix it?
Also I stacked with writing method with JPA that should find all Lesson by Group_id and Date(or startDate-endDate) and sort it: first by date, second- by TimeSlot_number.
Can it be written with JPA?
Thanks in advance.
Don't throw stones, I'm just getting to know Spring JPA.
I have 2 entities linked together using oneToMany mapping. In the Dao layer when i apply restrictions on the linked entity it fetches all the results. It seems that the restrictions are not working on the linked entity. I want to apply restrictions on both entities.
DAO
Criteria criteria = createEntityCriteria()
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.eq("status" , "APPROVED"))
.addOrder(Order.desc("approvedAt"))
.createAlias("purchaseDemandDetails" , "pds")
.add(Restrictions.ge("pds.approvedQuantity" , 1));
return criteria.list();
PurchaseDemand.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
#JoinColumn(name = "created_by", referencedColumnName = "id")
private User createdBy;
#Column(name = "created_at")
private Date createdAt;
#ManyToOne
#JoinColumn(name = "updated_by" , referencedColumnName = "id")
private User updatedBy;
#Column(name = "updated_at")
private Date updatedAt;
#ManyToOne
#JoinColumn(name = "approved_by" , referencedColumnName = "id")
private User approvedBy;
#Column(name = "approved_at")
private Date approvedAt;
#Column(name = "status")
private String status;
#OneToMany(mappedBy = "purchaseDemand", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<PurchaseDemandDetail> purchaseDemandDetails = new HashSet<PurchaseDemandDetail>();
public void setPurchaseDemandDetails(Set<PurchaseDemandDetail> purchaseDemandDetails)
{
this.purchaseDemandDetails.addAll(purchaseDemandDetails);
}
public Set<PurchaseDemandDetail> getPurchaseDemandDetails()
{
return this.purchaseDemandDetails;
}
PurchaseDemandDetail.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
#JoinColumn(name = "purchase_demand_id",referencedColumnName = "id")
#JsonIgnore
private PurchaseDemand purchaseDemand;
#ManyToOne
#JoinColumn(name = "product_id",referencedColumnName = "id")
private Product product;
#Column(name = "requested_quantity", nullable = false)
#NotNull(message = "Quantity is required")
private int requestedQuantity;
#Column(name = "approved_quantity", nullable = false)
#NotNull(message = "Quantity is required")
private int approvedQuantity;
}
I following have hibernate entities:
#Entity
#Table(name = "News")
public final class News implements Serializable, IEntity {
private static final long serialVersionUID = 3773281197317274020L;
#Id
#SequenceGenerator(name = "NEWS_SEQ_GEN", sequenceName = "NEWS_SEQ")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "NEWS_SEQ_GEN")
#Column(name = "NEWS_ID", precision = 0)
private Long newsId; // Primary key
#Column(name = "TITLE")
private String title;
#Column(name = "SHORT_TEXT")
private String shortText;
#Column(name = "FULL_TEXT")
private String fullText;
#Temporal(TemporalType.DATE)
#Column(name = "CREATION_DATE")
private Date creationDate;
#Temporal(TemporalType.DATE)
#Column(name = "MODIFICATION_DATE")
private Date modificationDate;
#OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
#JoinColumn(name = "NEWS_ID", updatable = false, referencedColumnName = "NEWS_ID")
#OrderBy("creationDate ASC")
private List<Comment> commentsList;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "NEWS_TAG", joinColumns = { #JoinColumn(name = "NEWS_ID") }, inverseJoinColumns = { #JoinColumn(name = "TAG_ID") })
private Set<Tag> tagSet;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "NEWS_AUTHOR", joinColumns = { #JoinColumn(name = "NEWS_ID") }, inverseJoinColumns = { #JoinColumn(name = "AUTHOR_ID") })
private Set<Author> author;
And the second:
#SequenceGenerator(name = "COMMENTS_SEQ", sequenceName = "COMMENTS_SEQ")
#Entity
#Table(name = "Comments")
public class Comment implements Serializable, IEntity {
private static final long serialVersionUID = 3431305873409011465L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COMMENTS_SEQ")
#Column(name = "COMMENT_ID", precision = 0)
private Long commentId; // Primary key
#Column(name = "NEWS_ID")
private Long newsId;
#NotEmpty
#NotNull
#Column(name = "COMMENT_TEXT")
private String commentText;
#Temporal(TemporalType.DATE)
#Column(name = "CREATION_DATE")
private Date creationDate;
When I'm trying to remove entity News, I get the exception ORA-02292: integrity constraint (ROOT.SYS_C007062) violated - child record found. So, if I remove the property "updatable = false" it tries to set nullable fields into property Comment. What is my mistake? Please, help.
Thanks.
Because your news records have a one to one or one to many relation with comments. You most likely did not specifcy a CACASDE ON DELETE clause while defining your table. in order to delete entity NEWS you have to make sure that all of its related comments records are deleted or are referencing another NEWS record.
basicaly the definition of the ORA 02292 exception.
I've an entity on OpenJPA 2.0
#Entity
#Table(name = "os_wfentry")
#SequenceGenerator(name = "jwe_seq", sequenceName = "jwe_seq", initialValue = 10, allocationSize = 1)
public class JPAWorkflowEntry implements WorkflowEntry, Serializable {
private static final long serialVersionUID = -755511983025049452L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jwe_seq")
private long id;
#Column(name = "name")
private String workflowName;
#Column(name = "state")
private Integer workflowState;
#Column(name = "version")
private Integer version;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "entry")
private final List<JPACurrentStep> currentSteps;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "entry")
private final List<JPAHistoryStep> historySteps;
public JPAWorkflowEntry() {
currentSteps = new ArrayList<>();
historySteps = new ArrayList<>();
}
...
and on JPACurrent and JPAHistory step I've inserted:
#ManyToOne
#Column(name = "entry_id")
protected JPAWorkflowEntry entry;
It is all correct (in theory); but when I try to save (or update) a new instance of JPAWorkflowStore, having a NOT EMPTY list of (current or history) steps, list of steps attribute is not persistend on db and it always an empty list. Can You help me?? What am I doing wrong??
You need to specify #JoinColumn(name = "id", nullable = false) for your JPACurrent and JPAHistory.
What you have done is #Column(name = "entry_id") i dont see "entry_id" mapping to any cölumn in JPAWorkflowEntry