An association from the table prestamos refers to an unmapped class - spring

So i'm getting this error with this two OneToOne.
An association from the table prestamos refers to an unmapped class
#MapsId
#OneToOne
#JoinColumn( name = "id_copia", referencedColumnName = "id_copia")
#JsonIgnoreProperties({"libro"})
private Copias copias;
#OneToOne(mappedBy = "copias")
#JsonIgnoreProperties({"copias"})
private Prestamos prestamos;

Related

The annotation #OneToMany is disallowed for this location trying to use mapped by to join a manytoone to a onetomany

The code is this one. As the title says i want to join a ManyToOne to a OneToMany.
#OneToMany(cascade = CascadeType.ALL,mappedBy = "libro"
#ManyToOne
#JoinColumn(name = "id_libros", referencedColumnName = "id_libros")
#JsonIgnoreProperties({"copias"})
private Libro libro;

In Spring Boot 2, is it possible to auto-generate a JoinTable with a unique constraint?

I'm using Spring Boot 2 and PostGres 10. I have created the following entities, Roles and Privileges,
#Data
#Entity
#Table(name = "Roles")
public class Role {
public enum Name {
USER,
ADMIN
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(unique=true)
#Enumerated(EnumType.STRING)
private Name name;
#ManyToMany
#JoinTable(
name = "roles_privileges",
joinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;
}
Privilege is
#Data
#Entity
#Table(name = "Privileges")
public class Privilege {
public enum PrivilegeName {
SUPER_ADMIN,
USER
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(unique=true)
#Enumerated(EnumType.STRING)
private PrivilegeName name;
#ManyToMany(mappedBy = "privileges")
private Collection<Role> roles;
}
Then I have this in my application.properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://${PG_DB_HOST:localhost}:5432/${PG_DB_NAME}
spring.datasource.username=${PG_DB_USER}
spring.datasource.password=${PG_DB_PASS}
When my tables are generated, the roles_privileges table is generated like so ...
cardmania=# \d roles_privileges ;
Table "public.roles_privileges"
Column | Type | Modifiers
--------------+------+-----------
role_id | uuid | not null
privilege_id | uuid | not null
Foreign-key constraints:
"fk5duhoc7rwt8h06avv41o41cfy" FOREIGN KEY (privilege_id) REFERENCES privileges(id)
"fk629oqwrudgp5u7tewl07ayugj" FOREIGN KEY (role_id) REFERENCES roles(id)
Are there any other annotations or other Java code I can add so that when my join table is created, the role_id/privilege_id has a unique key generated?
To force Hibernate to create a primary key with both columns, you have to change Collection by Set
public class Role {
#ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable(
name = "roles_privileges",
joinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "privilege_id", referencedColumnName = "id"))
private Set<Privilege> privileges;
}
And:
public class Privilege {
#ManyToMany(mappedBy = "privileges")
private Set<Role> roles;
}
You will not see a unique constraint but you will see the following table
create table roles_privileges (
role_id binary not null,
privilege_id binary not null
)
But you can explicitly declare your unique constraint
#ManyToMany
#JoinTable(
name = "roles_privileges",
joinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "privilege_id", referencedColumnName = "id"),
uniqueConstraints = #UniqueConstraint(columnNames = {"role_id",
"privilege_id"},
name = "rolesPrivilegesConstraint")
)
private Collection<Privilege> privileges;

Cannot delete or update a parent row HIBERNATE one to many

I'm getting this error when I try to delete a pet. This pet, has visits (child) but I have defined CASCADE.ALL in pet entity. Any idea ?
ERROR:
Cannot delete or update a parent row: a foreign key constraint fails (web_customer_tracker.visits, CONSTRAINT visits_ibfk_1 FOREIGN KEY (pet_id) REFERENCES pets (pet_id))
#Entity
#Table(name = "pets")
public class Pet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "pet_id")
private int pet_id;
.....
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "visit_id")
private Set<Visit> visits;
Visit class:
#Entity
#Table(name = "visits")
public class Visit {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "visit_id")
private int visit_id;
#ManyToOne
#JoinColumn(name = "pet_id")
private Pet pet;
....
you are using mappedBy in a wrong way
the mappedBy refers to the object name in the opposite side
like this
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "pet")
private Set<Visit> visits;
or if you want to map it by the JoinColum try this
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "pet_id")
private Set<Visit> visits;

Foreign key must have same number of columns as the referenced primary key for manyToMany

here job has a set of employees, and employee have a set of jobs, but Spring give me this exception
Caused by: org.hibernate.MappingException: Foreign key
(FK1kec5bwba2rl0j8garlarwe3d:account [employee_id])) must have same
number of columns as the referenced primary key (employee
[job_id,employee_id])
this is my employee class :
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id ;
private String firstname ;
private String lastname ;
private String email ;
private String phone ;
private String address ;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "account_id")
private Account account ;
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#ManyToOne
#JoinColumn(name = "departement_id")
#JsonIgnore
private Departement departement ;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "jobs", joinColumns = #JoinColumn(name = "employee_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "job_id", referencedColumnName = "id"))
private Set<Job>jobs ;
....
}
and here is my job class :
#Entity
#Inheritance
public abstract class Job {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id ;
private String status ; // (pending or done)
private Date date ;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "employee", joinColumns = #JoinColumn(name = "job_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "employee_id", referencedColumnName = "id"))
private Set<Employee> employee ;
#ManyToOne
#JoinColumn(name = "BusinnesPartner_id")
#JsonIgnore
private BusineesPartner busineesPartner ;
}
Please can you explain to me why I get this exception.
#JoinTable annotation should be used in the owning entity side , in the other side you should not have #JoinTable , you need to have mappedBy to define the reverse relation since you are establishing a bidirectional relation is if the Job is the owning entity you need to modify Employee pojo
#ManyToMany(cascade = CascadeType.ALL, mappedBy="employee")
private Set<Job>jobs ;

Hibernate - map a row to either of two subclasses

I have a Superclass
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "entity_type", discriminatorType = DiscriminatorType.STRING)
#Table(name = "my_super")
public abstract class MySuper{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "super_id")
private Long id;
}
and two subclasses
#Entity
#DiscriminatorValue("sub1")
public class Sub1 extends MySuper {}
#Entity
#DiscriminatorValue("sub2")
public class Sub2 extends MySuper {}
Now if another class has both of these subclasses in it, is it possible to instantiate one of them through the same join table - same row ??
For instance:
#Entity
#Table(name = "caller")
public class Caller{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "caller_id")
Long id;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "caller_super", joinColumns = #JoinColumn(name = "caller_id"), inverseJoinColumns = #JoinColumn(name = "super_id"))
private Set<Sub1> sub1s;
#ManyToOne(fetch = FetchType.LAZY)
#JoinTable(name = "caller_super", joinColumns = #JoinColumn(name = "caller_id"), inverseJoinColumns = #JoinColumn(name = "super_id"))
Sub2 sub2;
}
I keep getting this error when trying to instantiate a Caller Object:
org.springframework.orm.hibernate3.HibernateSystemException: could not set a field value by reflection setter of my.test.Caller.sub2; nested exception is org.hibernate.PropertyAccessException: could not set a field value by reflection setter of my.test.Caller.sub2
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:102)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:368)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
nested exception is org.hibernate.PropertyAccessException: could not set a field value by reflection setter
i think this two line shouldnt be same
#JoinTable(name = "caller_super", joinColumns = #JoinColumn(name = "caller_id"), inverseJoinColumns = #JoinColumn(name = "super_id"))
private Set<Sub1> sub1s;
--
#JoinTable(name = "caller_super", joinColumns = #JoinColumn(name = "caller_id"), inverseJoinColumns = #JoinColumn(name = "super_id"))
private Sub2 sub2;
because they are not same entity and their join table should be different. For ManyToMany relationship type is Sub1 but if you try to put them same table hibernate will try to put Sub2 to sub1s . But it is not vaild. Try to change your join table. For ManyToOne relationship.

Resources