Hibernate find by enum - java

I have 2 classes with One-to-Many relationship
#javax.persistence.Entity
#TypeDef(name = "InquiryIdType", typeClass = InquiryIdType.class)
public class Inquiry implements Entity
{
#javax.persistence.Id
#Type(type = "InquiryIdType")
#Column(name = "id", columnDefinition = DB_ENTITY_ID_TYPE)
private InquiryId id;
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "conference_session_id", nullable = false)
private ConferenceSession conferenceSession;
#Column(name = "state", nullable = false)
#Enumerated(EnumType.STRING)
private QuizStateType quizStateType;
and
public enum QuizStateType
{
IN_PROGRESS(0),
FINISHED(1),
NOT_STARTED(2),
DELETED(3);
public int value;
QuizStateType(int value)
{
this.value = value;
}
}
I need to find "Inquiry" by the Conference session Id_id and QuizStateType (is Deleted). I try, but swears at the context.
nested exception is
org.springframework.data.mapping.PropertyReferenceException: No
property is found for type QuizStateType! Traversed path:
Inquiry.quizStateType.
public interface InquiryRepository extends JpaRepository<Inquiry, UUID>
{
List<Inquiry> findByConferenceSession_idAndQuizStateTypeIs_DELETED (UUID conferenceSessionId);
}

Related

Java spring mappedBy reference an unknown target entity property

I have one exception, which is I have no mapping on my table. I have this Exeption
Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-service.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: org.openmrs.module.queue.model.Queue.queue_clinic in org.openmrs.module.queue.model.QueueClinic.queue
I have a table called queue with a foreign key called queue_clinic_id and another table called queue_clinicwith a primary key queue_clinic_id
Queue entity is here:
#EqualsAndHashCode(callSuper = true)
#Data
#Entity
#Table(name = "queue")
public class Queue extends BaseChangeableOpenmrsMetadata {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "queue_id")
private Integer queueId;
#ManyToOne
#JoinColumn(name = "location_id", nullable = false)
private Location location;
#ManyToOne
#JoinColumn(name = "service", referencedColumnName = "concept_id", nullable = false)
private Concept service;
#ManyToOne
#JoinColumn(name = "queue_clinic_id", nullable = true)
public QueueClinic queueClinic;
#OneToMany(mappedBy = "queue", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#Where(clause = "voided = 0 and (started_at <= current_timestamp() and ended_at is null)")
private List<QueueEntry> queueEntries;
#Override
public Integer getId() {
return getQueueId();
}
#Override
public void setId(Integer id) {
this.setQueueId(id);
}
}
And queue clinic entity is here :
#EqualsAndHashCode(callSuper = true)
#Data
#Entity
#Table(name = "queue_clinic")
public class QueueClinic extends BaseChangeableOpenmrsMetadata {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "queue_clinic_id")
private Integer queueClinicId;
#Override
#OneToMany(mappedBy = "queue_clinic", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#Where(clause = "voided = 0 and (started_at <= current_timestamp() and ended_at is null)")
private List<Queue> queue;
#Override
public Integer getId() {
return getQueueClinicId();
}
#Override
public void setId(Integer id) {
this.setQueueClinicId(id);
}
}
What im i doing wrong? Any assistance will be appreciated.
You have to reference the property fro the Queueclass
#OneToMany(mappedBy = "queueClinic", ...

Transform a composite id into a simple id Entity Hibernate

I'm working with Java 1.7, JBOSS EAP 6.4, hibernate jpa 2.0 and database oracle.
I'm trying to modify the composite id of an entity into a simple id.
Original Classes
#Entity
#Table(name = "FOO_BAR")
#IdClass(FooBarId.class)
public class FooBar{
#ManyToOne
#JoinColumn(
name = "COD_FOO",
updatable = false,
insertable = false)
#JsonIgnore
private Foo foo;
#ManyToOne
#JoinColumn(
name = "COD_BAR",
updatable = false,
insertable = false)
#JsonIgnore
private Bar bar;
#Id
#Column(name = "COD_FOO")
private String codFoo;
#Id
#Column(name = "COD_BAR")
private String codBar;
//getter and setter
}
public class FooBarId implements Serializable {
private String codFoo;
private String codBar;
public String getCodFoo() {
return codFoo;
}
public void setCodFoo(String codFoo) {
this.codFoo = codFoo;
}
public String getCodBar() {
return codBar;
}
public void setCodBar(String codBar) {
this.codBar = codBar;
}
}
New Classes
#Entity
#Table(name = "FOO_BAR")
public class FooBar{
#Id
private Long Id;
#ManyToOne
#JoinColumn(
name = "COD_FOO",
updatable = false,
insertable = false)
#JsonIgnore
private Foo foo;
#ManyToOne
#JoinColumn(
name = "COD_BAR",
updatable = false,
insertable = false)
#JsonIgnore
private Bar bar;
#Column(name = "COD_FOO")
private String codFoo;
#Column(name = "COD_BAR")
private String codBar;
//getter and setter
}
#Entity
#Table(name = "FOO_BAR_OTHER")
public class FooBarOther{
#Id
#Column(name = "ID")
private Long id;
#Column(name = "DATA")
private String data;
#ManyToOne
#JoinColumn(
name = "ID_FOO_BAR",
referencedColumnName = "ID",
insertable = false,
updatable = false)
private FooBar fooBar;
}
No problems in the build phase.
In the deploy phase i have the following error:
[PersistenceUnit: PersistenceUnit] Unable to build EntityManagerFactory
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: PersistenceUnit] Unable to build EntityManagerFactory
Caused by: org.hibernate.MappingException: Foreign key (FK_ljn0q2iefn1qh0dutifext8fj:FOO_BAR_OTHER [ID_FOO_BAR])) must have same number of columns as the referenced primary key (FOO_BAR [COD_FOO,COD_BAR])"}}
something saved the composite key and I can't delete it.
I tried to create a new class FooBar2 with same table FOO_BAR, same error.
I tried to create a class FooBar2 with only Id and same table, same error.
I tried to drop all database constraint, same error.
The only thing that worked was creating a new copy table of the original FOO_BAR2.
How can I fix the problem using the original table?

Hibernate #ManyToOne on non-primary keys of parent entities fetching parent entities too

Facing a strange issue while using #ManyToOne on non-primary keys of parent entities. When i fetch child entity hibernate is fetching parent entity too even though it is asked to fetch that lazily and I didn't query anything from parent entity.
Here is the example entity that I am using
Property Entity is the parent entity which has a column property_id and it is non-primary key.
public class Property extends AbstractEntity implements Serializable {
private static final long serialVersionUID = 8412320472079820864L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
Long id;
#Column(name = "property_id")
public Long propertyId;
#NotNull(message = "Name can't be null")
#Size(max = 100)
#Column(name = "name")
public String name;
Now I have a Room entity which is mapped with Property entity via column property_id.
public class Room extends AbstractEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
Long id;
#Column(name = "name")
private String name;
#Column(name = "size")
private String size;
#Column(name = "room_type")
private RoomType roomType = RoomType.STANDARD_ROOM;
#ManyToOne(targetEntity = Property.class, fetch = FetchType.LAZY)
#JoinColumn(name = "property_id", referencedColumnName = "property_id", nullable = false)
private Property property;
#Column(name = "priority")
private Integer priority;
Now when I fetch Room hibernate hits database to fetch property too.
Can someone please explain what is it that I am missing?
I tried implementing interceptor still no luck
#ManyToOne(fetch = FetchType.LAZY,optional = false)
#JoinColumn(name = "property_id", referencedColumnName = "property_id", insertable = false, updatable = false)
#LazyToOne(LazyToOneOption.NO_PROXY)
public Property getProperty() {
if (interceptor != null) {
return (Property) interceptor.readObject(this, "property", property);
}
return property;
}
public void setProperty(Property property) {
if (interceptor != null) {
this.property = (Property)interceptor.writeObject(this, "property", this.property, property);
return;
}
this.property = property;
}
P.s: I tried to use #NaturalId annotation too but it didn't worked.

Can't save entity Embeddable Id

I have EcranChamp entity
#Entity
#IdClass(EcranChampId.class)
public class EcranChamp {
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ecran")
Ecran ecran;
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "champ")
Champ champ;
...
And EcranChampId
#Embeddable
public class EcranChampId implements Serializable {
private Champ champ;
private Ecran ecran;
...
Every time i am trying to save an EcranChamp element i have this following error
2018-09-25 12:15:42.889 WARN 14216 --- [nio-8092-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to convert request element: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Long' to required type 'com.kepler.portailclient.domain.model.Ecran' for property 'ecran'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Long' to required type 'com.kepler.portailclient.domain.model.Ecran' for property 'ecran': no matching editors or conversion strategy found
2018-09-25 12:15:42.889 WARN 14216 --- [nio-8092-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Long' to required type 'com.kepler.portailclient.domain.model.Ecran' for property 'ecran'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Long' to required type 'com.kepler.portailclient.domain.model.Ecran' for property 'ecran': no matching editors or conversion strategy found
Try something like this:
#Entity
#Table(name = "<entity name>")
public class EcranChamp {
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "id_ecran", column = #Column(name =
"<column name>", nullable = false)),
#AttributeOverride(name = "id_champ", column = #Column(name = "<column name>", nullable = false)) })
EcranChampId id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_ecran")
Ecran ecran;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_champ")
Champ champ;
//getters & setters
}
#Embeddable
public class EcranChampId implements Serializable {
#Column(name = "id_champ", nullable = false)
private Long id_champ;
#Column(name = "id_ecran", nullable = false)
private Long id_ecran;
//getters & setters
}
You shoud use #EmbeddedId annotation.
Please, change your EcranChampId class to this:
#Embeddable
public class EcranChampId implements Serializable {
#ManyToOne
private Champ champ;
#ManyToOne
private Ecran ecran;
//getters and setters
}
And change your EcranChamp class to this:
#Entity
#Table(name = "champ_has_ecran_table_name")
#AssociationOverrides({
#AssociationOverride(name = "pk.champ", joinColumns = #JoinColumn(name = "champ_id"))
#AssociationOverride(name = "pk.ecran", joinColumns = #JoinColumn(name = "ecran_id"))
})
public class EcranChamp {
#EmbeddedId
private EcranChampId pk;
public EcranChamp() {
pk = new EcranChampId();
}
public EcranChampId getPk() {
return pk;
}
public void setPk(EcranChampId pk) {
this.pk = pk;
}
#Transient
public Champ getChamp() {
return pk.getChamp();
}
public void setChamp(Champ champ) {
pk.setChamp(champ);
}
#Transient
public Ecran getEcran() {
return pk.getEcran();
}
public void setChamp(Ecran ecran) {
pk.setEcran(ecran);
}
}
And use it like this:
public class Champ {
#OneToMany(mappedBy = "pk.champ")
private Collection<EcranChamp> ecranChamps;
//getters and setters
}
Also, if EcranChamp or EcranChampId has no other fields i will recommend you to use #ManyToMany annotation instead EcranChamp class like this:
public class Champ {
#ManyToMany
#JoinTable(
name = "champ_has_ecran_table_name",
joinColumns = #JoinColumn(name = "champ_id", referencedColumnName = "id", nullable = false),
inverseJoinColumns = #JoinColumn(name = "ecran_id", referencedColumnName = "id", nullable = false)
)
private Collection<Ecran> ecrans;
//getters and setters
}

Many to Many in JPA and EBean

I'm trying to make a many to many relationship using EBean in Play2 and I have an issue where EBean trows an error saying my class is not registered.
Heres my mapping classes:
#Entity
public class Booking extends Model {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
//... other fields
}
#Entity
public class Store extends Model {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
//... other fields
}
#Embeddable
public class ComissionId {
#ManyToOne(targetEntity = Booking.class, optional = false)
#PrimaryKeyJoinColumn(name = "booking_id", referencedColumnName = "id")
private Booking booking;
#ManyToOne(targetEntity = Store.class, optional = false)
#PrimaryKeyJoinColumn(name = "store_id", referencedColumnName = "id")
private Store store;
}
#Entity
#AssociationOverrides({
#AssociationOverride(name = "id.booking", joinColumns = #JoinColumn(name = "booking_id")),
#AssociationOverride(name = "id.store", joinColumns = #JoinColumn(name = "store_id"))
})
public class StoreComission extends Model {
#EmbeddedId
private ComissionId id;
#Column(nullable = false)
private double value;
#Column(nullable = false)
private Date date;
}
The error:
java.lang.RuntimeException:
Error reading annotations for models.ids.ComissionId
Caused by: java.lang.RuntimeException:
Error with association to [class models.Booking] from [models.ids.ComissionId.booking].
Is class models.Booking registered?
In my application.conf I've put ebean.default="models.*" so all this classes should be registered right? (I've tried to move the ComissionId from the package models.ids to models, but the same error ocurred)
You have this error because of #ManyToOne annotations inside your ComissionId class. To make this code work you have to move these relations to StoreComission class. In ComissionId class you should leave only identifiers. In StoreComission class #ManyToOne relation are mapped to the same columns as fields from composite key. But they have attributes 'insertable' and 'updateable' set to false to prevent column duplication.
Here is corrected working code for above scenario:
StoreComission class:
#Entity
public class StoreComission extends Model {
public StoreComission() {
id = new ComissionId();
}
#EmbeddedId
private ComissionId id;
#Column(nullable = false)
public double value;
#Column(nullable = false)
public Date date;
#ManyToOne
#JoinColumn(name = "booking_id", insertable = false, updatable = false)
private Booking booking;
#ManyToOne
#JoinColumn(name = "store_id", insertable = false, updatable = false)
private Store store;
public void setBooking(Booking aBooking) {
booking = aBooking;
id.booking_id = aBooking.id;
}
public Booking getBooking() {
return booking;
}
public void setStore(Store aStore) {
store = aStore;
id.store_id = aStore.id;
}
public Store getStore() {
return store;
}
}
ComissionId class:
#Embeddable
public class ComissionId {
public int booking_id;
public int store_id;
#Override
public int hashCode() {
return booking_id + store_id;
}
#Override
public boolean equals(final Object obj) {
return super.equals(obj);
}
}

Categories

Resources