Hibernate One-to-Many mapping by date range? - java

I want to change Train.trainFares from transient to mapped to the TrainFare class. However, I want to limit the TrainFares to those that are active for the Train.ddate. How do I do this?
I have found a Hibernate Jira issue which I believe might be the source of my problems. Has anyone else come across this issue? Did you find a workaround?
#Entity
#Table(name = "TRAIN")
public class Train {
#EmbeddedId
private TrainPK id;
#Column
private String trainType;
#Transient
private List<TrainFare> trainFares;
#Embeddable
public static class TrainPK {
#Column
private String company;
#Column
private Date departDate;
#Column
private String trainNumber;
}
... setters & getters
}
#Entity
#Table(name = "SEATRATE")
public class SeatRate {
#EmbeddedId
private SeatRatePK id;
#Column
private Date expiryDate;
#Column
private String trainNumber;
#Embeddable
public static class SeatRatePK {
#Column
private String company
#Column
private Date effectiveDate;
}
... setters & getters
}

Related

OneToOne and OneToMany not storing Parent Id (IdClass)

I am currently working on a project with following data structure:
public class PinaColadaId implements Serializable {
private UUID id;
#Temporal(TemporalType.TIMESTAMP)
private Date time;
// Constructor + Getters and Setters
}
#Entity
#Table(name = "pina_coladas")
#IdClass(PinaColadaId.class)
public class PinaColadaEntity {
#Column(columnDefinition = "char(255)")
#Type(type="org.hibernate.type.UUIDCharType")
private #Id UUID id;
private #Id #Temporal(TemporalType.TIMESTAMP) Date time;
#OneToOne(mappedBy = "entityID", cascade=CascadeType.ALL)
private PineappleWrapper pineapple;
#OneToMany(mappedBy = "entityID", cascade=CascadeType.ALL)
private List<CoconutWrapper> coconuts;
// Constructor + Getters and Setters
}
#Entity
public class PineappleWrapper {
private #Id #GeneratedValue long id;
private String manufacturer;
private String origin;
#OneToOne
private PinaColadaEntity entityID;
// Constructor + Getters and Setters
}
#Entity
public class CoconutWrapper {
private #Id #GeneratedValue long id;
private int shipmentNumber;
private int juice;
#ManyToOne
private PinaColadaEntity entityID;
// Constructor + Getters and Setters
}
The issue is that Spring Boot together with Hibernate and JPA correctly generate all the tables in my database, however when I attempt to store PineappleWrapper or CoconutWrapper, it stores all the values of PineappleWrapper and/or CoconutWrapper except for the id and time of the parent. The columns are generated yet they store the value "null".
Any and all help is much appreciated, -AwesomeDude091
Edit: I am aware of the JoinColumn annotation and it proposed implementation in my Wrapper classes, but I do not know how to use them with my two ID variables (id and time)

Add foreign key using hibernate and jpa

Those are my classes:
#Entity
#Table(name="assessment")
public class AssesmentProperties {
#Id
#Column(name="AssessmentId")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long AssessmentId;
#Column(unique=true,nullable=false)
private String AssessmentName;
private String AssessmentLevel;
private String Specialization;
private int time;
private String keywords;
private int NoOfSections;
//getters and setters
}
#Embeddable
public class SettingsPrimary implements Serializable {
private Long AssessmentId;
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long Section;
//getters and setters
}
#Entity
#Table(name="section")
public class SectionProperties {
#EmbeddedId
private SettingsPrimary PrimaryKey;
private String SectionType;
private int Weightage;
private int time;
private int NoOfQuestions;
//getters and setters
}
In the table section I need to create assessment_id as FK to assessment table and set cascade on delete. I have tried to do it with different ways but without success.
Maybe this could help you.
#Entity
#Table(name="section")
public class SectionProperties {
#Id
private Long PrimaryKey;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "assessment_id", referencedColumnName="AssessmentId")
private AssesmentProperties AssesmentProperties;
private String SectionType;
private int Weightage;
private int time;
private int NoOfQuestions;
//getters and setters
}
I changed the SectionProperties id to a Long and mapped the AssessmentProprties into a ManytoOne prop.
This way, always that a AssessmentProperties binded to a Section will be deleted, the associated SectionProperties will too.

composite key for the table using association annotation

I am new to hibernate and I am trying to implement a basic application that uses this schema (it does not follow the notation I just use it for clarity)
Here is the my classes
#Entity
#Table(name = "race")
public class Race {
#Id
#GeneratedValue
private UUID id;
private String name;
}
#Entity
#Table(name="np_character")
public class NPCharacter {
#Id
#GeneratedValue
private UUID id;
#OneToOne
private Race race;
private String name;
private int age;
}
#Entity
#Table(name="main_female_character")
public class MainFemaleCharacter {
#Id
#GeneratedValue
private UUID id;
#OneToOne
private Race race;
private String name;
private int age;
}
#Entity
#Table(name="copulation_registry")
public class CopulationRegistry {
// ??
private NPCharacter npCharacter;
// ??
private MainFemaleCharacter femCharacter;
private int times;
}
But I ran into the problem with copulation_registry class. I used everywhere OneToOne annotation, instead of using references to keys. But what I should do here? Pairs of id_femPlayer and id_npCharacter are unique.
Should I use EmbeddedId annotation or is it possible somehow to use association annotations to represent the same relation?
You can annotate class CopulationRegistry with #IdClass
#Entity
#IdClass(CopulationRegistryKey.class)
#Table(name="copulation_registry")
public class CopulationRegistry {
#Id
private NPCharacter npCharacter;
#Id
private MainFemaleCharacter femCharacter;
private int times;
}
public class CopulationRegistryKey{
private NPCharacter npCharacter;
private MainFemaleCharacter femCharacter;
}

How to adjust relations between entities using Hibernate mapping?

I have such a simple scheme
and the following entities:
#Entity
public class Ticket {
#Id
#GeneratedValue
private Integer id;
#ManyToOne
private Event event;
#OneToOne
private User user;
#Embedded
private Seat seat;
private TicketState state;
private Float price;
// getters, setters, etc.
#Entity
public class Event {
#Id
#GeneratedValue
private Integer id;
#OneToOne
private Movie movie;
#Embedded
private Auditorium auditorium;
private LocalDateTime startDateTime;
#OneToMany
private Set<Ticket> tickets = new HashSet<>();
// getters, setters, etc.
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
#Enumerated(EnumType.STRING)
private UserRole role;
private String name;
private String email;
private Instant birthday;
#OneToMany
private List<Ticket> tickets = new ArrayList<>();
private boolean lucky;
// getters, setters, etc.
#Embeddable
public class Auditorium {
private Integer id;
private String name;
private Integer seatsNumber;
#ElementCollection
private List<Integer> vipSeats;
// getters, setters, etc.
Also these entities was added to hibernate.cfg.xml.
Than I run app I have the following exception:
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.epam.spring.core.domain.Event column: id (should be mapped with insert="false" update="false")
At first glance I don't see any duplications in Event, as mentioned in exception. What should I fix in entities mapping description to resolve the problem according my scheme? Thank you!
Both Event and Auditorium map to column named id.
Specify a different column name in Auditorium or use #AttributeOverride in Event to override the default name.
When you map an entity with annotations, you do not need to repeat yourself on hibernate.cfg.xml. Try to delete it e run your code again.
Updating my answer based on Dragan Bozanovic's, Auditorium should NOT have an #Id annotated field (but we can't see that from your code, if it has).

Hibernating - Generating part of a composite key

I have the following class:
#Entity
public class User {
#Embeddable
public static class Key implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
#Temporal(TemporalType.TIMESTAMP)
private Date effectiveDate;
#Column(unique = true)
private String name;
// Getters, Setters
}
#EmbeddedId
private Key key;
#Column(nullable = false)
private String password;
// Getters, Setters ...
}
I want the id field within key to be generated, unfortunately I can't find a way to do so. I've looked at similar questions here but I can't find the answer (all the solution proposed did not work in this case).

Categories