Java hibernate Exception: missing column - java

I have a PostgreSQL table and a data class representing the table. I am using annotations for mapping instead of mapping xml files. I deleted some columns as they are not required from both the db table and mapping class. But I get a runtime hibernate exception: missing column on the deleted columns. The columns are not referenced anywhere else, otherwise the compile would have failed. For now I added the columns back to the table (but not the class) and it works fine. Can anybody point the direction? I can post the code if you want but t is just a simple data class and a table.
Exception:
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'phaseRepository' defined in Servle
tContext resource [/WEB-INF/context/spring-entity.xml]: Cannot resolve reference to bean 'sessionFactory' while setting be
an property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/context/spring-entity.xml]: Invocation of init method failed; nested exception is
org.hibernate.HibernateException: Missing column: patient_given_name in public.patient_detail at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResol
ver.java:328) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionVal
ueResolver.java:106)
Entity Class:
#Entity
#Table(name = "patient_detail")
public class PatientDetail implements Serializable {
private static final long serialVersionUID = -7765251798211029654L;
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "patient_detail_id_seq")
#SequenceGenerator(name = " patient_detail_id_seq ", sequenceName = " patient_detail_id_seq ", allocationSize = 1)
private long id;
#Column(name = " templateId ")
private long templateId;
#Column(name = "description")
private String description;
#Column(name = "anatomical_name")
private String anatomicalName;
#Column(name = "additional_comments")
private String additionalComments;
#Column(name = "create_date")
private Date createDate;
#Column(name = "modified_date")
private Date modifiedDate;
#ManyToOne
#ForeignKey(name = "fk_patient_id")
#JoinColumn(name = "patient_id")
private Patient patient;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#Fetch(FetchMode.SELECT)
#JoinColumn(name = "patient_id")
private List<PatientPhase> phases;
.....
getters and setters

Related

Unable to find column with logical name in JPA Springboot [duplicate]

This question already has answers here:
Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed
(41 answers)
Closed 9 months ago.
There are two tables. Address inside Hotel. I have already mentioned OneToMany relation. But compiler throwing error.
Error creating bean with name 'entityManagerFactory' defined in class
path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.MappingException: Unable to find column with logical
name: addressId in org.hibernate.mapping.Table(address) and its
related supertables and secondary tables
Hotel.java
#AllArgsConstructor
#Data
#Entity
#Table(name = "hotels")
#NoArgsConstructor
public class HotelEntity {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "hote_id")
private String hotelId;
#Column(name = "hotel_name")
private String hotelName;
#Column(name = "build_date")
private Date buildDate;
#Column(name = "guest_type") #Enumerated(EnumType.STRING)
private GuestType guestType;
#Column(name = "room")
#OneToMany(targetEntity = RoomEntity.class,cascade = CascadeType.ALL)
#JoinColumn(name = "hotel_room", referencedColumnName = "roomId")
private List<Room> room;
#OneToOne(targetEntity = AddressEntity.class,cascade = CascadeType.ALL)
#JoinColumn(name = "hotel_address", referencedColumnName = "addressId")
private Address hotelAddress;
Address.java
#Entity
#Table(name = "ADDRESS")
#Getter
#Setter
#ToString
#RequiredArgsConstructor
public class AddressEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "address_id")
private String addressId;
#Column(name = "street_name")
private String streetName;
#Column(name = "city")
private String city;
#Column(name = "zip_code")
private String zipCode;
#Column(name = "country")
private String country;
}
I tried some changing in variable name also double checked if I am missing something. but looks I have followed same way as mentioned in other Stack Overflow questions. Am I missing something?
referencedColumnName shall refer to the #Column name and not java attribute name Change referencedColumnName value from addressId to address_id
#JoinColumn(name = "hotel_address", referencedColumnName = "address_id")
private Address hotelAddress;

Many to Many Spring MVC mappedBy reference an unknown target entity property

Good day everyone
I’m trying to create a relationship for the entities Shelter and Owner, many to many, but a mistake is climbing, I do not understand what's the matter
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#DynamicUpdate
#Entity
#Table(name = "owner")
public class Owner {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idOwner;
private String name;
private String address;
private String description;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(
name = "owner_shelter",
joinColumns = {#JoinColumn(name = "owner")},
inverseJoinColumns = {#JoinColumn(name = "shelter")}
)
private Set<Shelter> shelterOwner;
}
--
#Data
#DynamicUpdate
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Entity
#Table(name = "shelter")
public class Shelter {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String address;
private String description;
#ManyToMany(mappedBy = "shelter")
private Set<Owner> sheltersOwner;
}
and the error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: ru.itis.springbootdemo.models.Owner.shelter in ru.itis.springbootdemo.models.Shelter.sheltersOwner
Error message is explicit , this is not correct
#ManyToMany(mappedBy = "shelter")
private Set<Owner> sheltersOwner;
should be
#ManyToMany(mappedBy = "shelterOwner")
private Set<Owner> sheltersOwner;
mappedBy references the other side attribute name and in your code it is not correctly set.
problem is field name of the shelter in Owner class, it must be private Set<Shelter> shelter;
not private Set<Shelter> shelterOwner;

Compilation: Error creating bean with name 'entityManagerFactory'

I have this error when I compile. In test I don't have problem.
I have the dependency javax.xml.bind, jaxb-api.
Error:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory' defined in class
path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: mappedBy reference an unknown
target entity property:
com.endoorment.models.entity.AccessoryLang.accessory in
com.endoorment.models.entity.Accessory.accessorylang
Entities:
#Entity
#Table(name = "accessories")
public class Accessory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
#OneToMany(mappedBy = "accessory", cascade = CascadeType.ALL)
private Set<AccessoryLang> accessorylang = new HashSet<AccessoryLang>();
#Entity
#Table(name = "accessories_langs")
public class AccessoryLang implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private AccessoryLangId accessorylangid;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("accessoryId")
#JoinColumn(name = "accessories_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private Accessory accessory;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("langId")
#JoinColumn(name = "langs_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private Lang lang;
#Column(nullable = false, length = 45)
#NotEmpty
private String name;
The problem is that you have a many to many relationship which was mapped in your case as a many to one and one to many.
You have a many to many relationship between Accessory and Lang. JPA lets you better map it directly.
Please check this article or search for "JPA many to many mapping"
https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/

How to set a domain field as a list of numbers

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;
}

How can I correctly implement this Spring Data JPA named query that involves a JOIN between 2 tables?

I am working on a Spring application using Spring Data JPA. I am implemented the named query method to implement my queries. I am experiencing some difficulties trying to implement a named query that involves a join between 2 tables\entity classes.
So I have these 2 entity classes:
1) Room representing a room of an accomodation:
#Entity
#Table(name = "room")
public class Room implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;
#ManyToOne
#JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;
#Column(name = "room_number")
private String number;
#Column(name = "room_name")
private String name;
#Column(name = "room_description")
#Type(type="text")
private String description;
#Column(name = "max_people")
private Integer maxPeople;
#Column(name = "is_enabled")
private Boolean isEnabled;
// CONSTRUCTOR, GETTER AND SETTER METHODS
}
As you can see this class contains this field:
#ManyToOne
#JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;
that link many Room instance to a RoomTipology instancce.
2) Then I have RoomTipology entity class:
#Entity
#Table(name = "room_tipology")
public class RoomTipology implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "tipology_name")
private String name;
#Column(name = "tipology_description")
private String description;
#Column(name = "time_stamp")
private Date timeStamp;
#OneToMany(mappedBy = "roomTipology")
private List<Room> rooms;
#OneToOne(mappedBy = "roomTipology")
private RoomRate roomRate;
// CONSTRUCTOR, GETTER AND SETTER METHODS
}
Then I have this repository clas for the RoomTipology entity class, something like:
#Repository
#Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {
RoomTipology findByRoomTipology_Room(Room room);
}
I have try in this way but it can't work and I obtain the following error message:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roomTipologyDAO': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property roomTipology found for type RoomTipology!
I want to retrieve the related RoomTipology instance starting from the Room. Basically I want to translate this SQL query into a Spring Data JPA named query:
SELECT *
FROM `room_tipology` rt
INNER JOIN room r
ON rt.id = r.id_room_tipology_fk
WHERE r.id = 7
where r.id is the value of the id field of the Room entity.
I know that if I already have a Room object I can obtain this information doing:
room.getRoomTipology()
But sometimes I just have the id of a Room instance and I want directly retrieve the related RoomTipology object.
How can I do it using named query?
Name your method the way you think it should best be named, pass a roomId rather than a room, since that's your actual search parameter, and annotate the method with
#Query("select t from Room r join r.roomTypology t where r = :roomId")

Categories

Resources