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", ...
Related
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);
}
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.
I want to define one field within the question_response table as a list of numbers.
#Entity
public class QuestionResponse {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="question_response_id", nullable = false, updatable = false)
private Long question_response_id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_uuid")
private User users;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "question_id")
private Question questions;
private List<Long> questionAns;
}
But it gave the error of:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: question_response, for columns: [org.hibernate.mapping.Column(question_ans)]
I've also tried Set, but didn't work. Can anybody help me with this?
you can use this :
public class Answer{
#Column(name="id_response")
private long Idresponse;
#Column(name="response")
private String response;
#JsonIgnore
#ManyToOne
#JoinColumn(name="question")
private QuestionResponse questionResponse;
}
then in QuestionResponse class you can you use OneToMany relation as shown , it will work :
#Entity
public class QuestionResponse {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="question_response_id", nullable = false, updatable = false)
private Long question_response_id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_uuid")
private User users;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "question_id")
private Question questions;
#OneToMany(mappedBy = "answer", cascade = CascadeType.ALL)
private Set<Answer> answer;
}
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
}
I have a custom JPQL query in a Spring CrudRepository that's not working.
This is my entity class, PK class and CrudRepository interface for the entity:
#Entity(name = "TBL_PRINCIPAL_CREDENTIAL")
public class PrincipalCredential {
#EmbeddedId
private PrincipalCredentialPK principalCredentialPK;
// ...getter & setter for principalCredentialPK
}
#Embeddable
public class PrincipalCredentialPK implements Serializable {
#Column(name = "PRINCIPAL_TYPE_ID", nullable = false)
private String principalTypeID;
#Column(name = "PRINCIPAL_ID", nullable = false)
private String principalID;
#Column(name = "CREDENTIAL_ID", nullable = false)
private Integer credentialID;
#Column(name = "CREDENTIAL_TYPE_ID", nullable = false)
private String credentialTypeID;
// ...getters & setters for all fields...
}
#Transactional
public interface PrincipalCredentialRepository extends CrudRepository<PrincipalCredential, PrincipalCredentialPK> {
#Modifying
#Query("update PrincipalCredential pc set pc.principalCredentialPK.principalID =:newPrincipalID " +
"where pc.principalCredentialPK.principalID =:oldPrincipalID and pc.principalCredentialPK.principalTypeID =:principalType")
void updatePrincipalID(#Param("oldPrincipalID") String oldPrincipalID, #Param("newPrincipalID") String newPrincipalID,
#Param("principalType") String principalType);
}
When I start my project using SpringBoot the repository bean cannot be instantiated and I get the following exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'principalCredentialRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract void com.consorsbank.services.banking.caas.repositories.PrincipalCredentialRepository.updatePrincipalID(java.lang.String,java.lang.String,java.lang.String)!
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract void com.consorsbank.services.banking.caas.repositories.PrincipalCredentialRepository.updatePrincipalID(java.lang.String,java.lang.String,java.lang.String)!
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: PrincipalCredential is not mapped [update PrincipalCredential pc set pc.principalCredentialPK.principalID =:newPrincipalID where pc.principalCredentialPK.principalID =:oldPrincipalID and pc.principalCredentialPK.principalTypeID =:principalType]
Also for another repository this query is working, the difference is that the PK of the other entity is simpler and both ids are provided there...
#Entity
#Table(name = "TBL_PRINCIPALS")
public class Principal implements Serializable {
#EmbeddedId
private PrincipalPK principalPK;
#OneToOne
#JoinColumn(name = "PRINCIPAL_TYPE_ID", insertable = false, updatable = false)
private PrincipalType principalType;
#Column(name = "USER_ID")
private Integer userID;
#Column(name = "VALID_UNTIL")
private Date validUntil;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "ZAAS_TBL_PRINCIPAL_CREDENTIAL",
joinColumns = {#JoinColumn(name = "PRINCIPAL_ID"), #JoinColumn(name = "PRINCIPAL_TYPE_ID")},
inverseJoinColumns = {#JoinColumn(name = "CREDENTIAL_ID"), #JoinColumn(name="CREDENTIAL_TYPE_ID")})
public Set<Credential> credentials;
// ...getters and setters...
}
#Embeddable
public class PrincipalPK implements Serializable {
#Column(name = "PRINCIPAL_TYPE_ID", nullable = false)
private String principalTypeID;
#Column(name = "PRINCIPAL_ID", nullable = false)
private String principalID;
// ...getters and setters
}
#Transactional
public interface PrincipalsRepository extends CrudRepository<Principal, PrincipalPK> {
#Modifying
#Query("update Principal p set p.principalPK.principalID =:newPrincipalID " +
"where p.principalPK.principalID =:oldPrincipalID and p.principalPK.principalTypeID =:principalType")
void updatePrincipalID(#Param("oldPrincipalID") String oldPrincipalID, #Param("newPrincipalID") String newPrincipalID,
#Param("principalType") String principalType);
}
So the above query is working...
Could someone please point out what I'm missing for the query defined in the PrincipalCredentialRepository?
The entity definition seems to be wrong. Use the following annotations
#Entity
#Table(name = "TBL_PRINCIPAL_CREDENTIAL")
public class PrincipalCredential {
//...