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;
Related
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 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/
I have two objects. The company that can have multiple nested addresses.
#Entity
#Data
#Table(name = "company")
public class Company {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "phone")
private String phone;
#OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<Address> addresses;
}
Address class looks like this:
#Data
#Entity
#Table(name = "address")
#ToString(exclude = "company")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "postal_code")
private String postalCode;
#Column(name = "city")
private String city;
#Column(name = "street")
private String street;
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "company_id")
private Company company;
}
I want somehow if it's possible, make a dynamic query that searches through the nested collection property. I made a search method which uses example matcher but the result is wrong. Every time I got everything from DB, not only company with address postal code that I'm looking for.
My search method looks like this:
#PostMapping("/search")
public List<Company> search(#RequestBody final Company company){
return companyRepository.findAll(Example.of(company,
ExampleMatcher.matchingAny()
.withIgnoreNullValues()
.withIgnorePaths("id")
.withStringMatcher(ExampleMatcher.StringMatcher.STARTING)));
}
In my database, I have two objects and this is the result of the search:
As you can see I received everything from DB instead of the only first company which address postal code starts with 1.
Hi you can use Specification<T>
https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
For this you need to extend from interface JpaSpecificationExecutor:
public interface UserRepository extends JpaRepository<User> ,JpaSpecificationExecutor<User>{
}
And you also need to implement your custom Specification<T>
And then you can use repository.findAll(your impleneted Specification);
Spring docs :
https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaSpecificationExecutor.html
I think this is helpful.
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.