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/
Related
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;
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;
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 work with a Spring boot project and when I run, I get the following error,
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userSecurityService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Could not create query metamodel for method public abstract Ecommerce.entities.User Ecommerce.repository.UserRepository.findByUsername(java.lang.String)!
I assume the last lines are what is important in the error stack,
Could not create query metamodel for method public abstract Ecommerce.entities.User Ecommerce.repository.UserRepository.findByUsername(java.lang.String)!
I have the User repository provided below,
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
User findByEmail(String email);
}
The user entity is also provided,
#Entity
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userId", nullable = false, updatable = false)
private Long userId;
private String userName;
private String password;
private String firstName;
private String lastName;
#Column(name = "email", nullable = false, updatable = false)
private String email;
private String phone;
private boolean enabled = true;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
private ShoppingCart shoppingCart;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<UserShipping> userShippingList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<UserPayment> userPaymentList;
#OneToMany(mappedBy = "user")
private List<Order> orderList;
#JsonIgnore
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<UserRole> userRoles = new HashSet<>();
// ..............
// more lines of code for overriding the methods
}
What is the issue here and how to solve it?
In Spring JPA Repository, the auto-generated finders obey the naming convention as follows.
findBy<DataMember><Op>
<Op> can be Like,Between etc..
Apparently, the name of the method findByUsername should match with the property in the user entity. In the user entity class, I have used,
#Entity
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userId", nullable = false, updatable = false)
private Long userId;
private String userName;
}
After I changed to the username from the userName, the problem is solved. I have done this after consulting other SOF posts, but, I still seek for the better explanation.
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