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

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;

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;

#OneToMany targeting an unmapped class, but class is mapped

I'm setting up spring security, yet when I define a #OneToMany relationship I get the error:
Use of #OneToMany or #ManyToMany targeting an unmapped class: loginApi.users.Users.roles[Security.Roleinfo]
I've already tried most of the answers on here,
yes, I am importing from javax.persistance
yes, #Entity is on top of each class
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "users")
public class Users {
#Id
#Column(name="username")
private String username;
private String firstname;
private String lastname;
private int curreventid;
private String email;
private String password;
private int points;
private int phone;
// problem part
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "usersrole", joinColumns = {#JoinColumn(name = "username")}, inverseJoinColumns = {#JoinColumn(name = "roleid")})
private Set<Roleinfo> roles;
}
Here is the roleinfo class:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "roleinfo")
public class Roleinfo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int roleid;
private String roletitle;
}
right now I'm trying to join my usersrole table which has two columns containing the username and that user's role (roleid) with the user table.
any help would be appreciated!
Thanks #JB Nizet, after reading the docs I realized my security package wasn't under my springbootapp package, meaning the user class was never scanned for the #Entity flag.

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/

Spring boot / Hibernate problems with #UniqueConstraint

I have Spring boot 1.4.3 + Hibernate 5.0.11 + H2 database.
My application startup fails when I try to use #UniqueConstraint with certain values. Here is it. Response class is marked with #UniqueConstraint with columnNames "survey" and "user"
#Entity
#Table(name = "responses", uniqueConstraints = {#UniqueConstraint(columnNames = {"survey, user"}, name = "responses_survey_user_idx")})
public class Response extends BaseEntity
{
#NotNull
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "survey", nullable = false)
private Survey survey;
#NotNull
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "user", nullable = false)
private User user;
#NotNull
private String answers;// json serialized
}
Survey class:
#Entity
#Table(name = "surveys", uniqueConstraints = {#UniqueConstraint(columnNames = {"name"}, name = "surveys_name_idx")})
public class Survey extends BaseEntity{
#NotNull
#SafeHtml
#Length(min = 3)
private String name;
#NotNull
#SafeHtml
#Length(min = 3)
private String description;
#OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "survey")
private List<Response> responses;
}
User class:
#Entity
#Table(name = "users", uniqueConstraints = {#UniqueConstraint(columnNames = "login", name = "users_unique_email_idx")})
public class User extends BaseEntity {
#NotEmpty
#SafeHtml
private String login;
#NotEmpty
#Length(min = 8)
#SafeHtml
private String password;
#OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "user")
private List<Response> responses;
}
The error I get is:
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 org.hibernate.AnnotationException: Unable to create unique key constraint (survey, user) on table responses: database column 'survey, user' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
I've tried to change names of columns in Response class, but it didn't help.
It work only when I remove #UniqueConstraint in this class at all .
Any ideas how to deal with this?
The column names in your unique constraint should not be comma separated but rather separate String values in an array (see http://docs.oracle.com/javaee/6/api/javax/persistence/UniqueConstraint.html):
#Table(
name="EMPLOYEE",
uniqueConstraints=
#UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})
)

Hibernate One-to-one PrimaryKeyJoinColumn Wrong type for class

I have a two entities and relation between them OneToOne:
#Entity
#Getter
#Setter
public class Master {
#Id
private String id;
private String name;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "master", optional = false)
private Slave slave;
}
#Entity
#Getter
#Setter
public class Slave {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "id_slave")
private Integer id;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_master")
#PrimaryKeyJoinColumn
private Master master;
}
MAIN:
Master master = em.find(Master.class, "TEST_ID");
When I run this code I get
java.lang.IllegalArgumentException: Provided id of the wrong type for class entity.Slave. Expected: class java.lang.Integer, got class java.lang.String
I see that is due to #PrimaryKeyJoinColumn exists, who knows how to prevent this exception and if it is possible to point out type for PrimaryKeyJoinColumn. I can not remove #PrimaryKeyJoinColumn cause I want to have laziness.

Categories

Resources