in spring boot i want to achieve that if i can access employee table from employee_personal_detail table and also i can access
employee_persona_detail table from employee vice-versa while adding
data Why Foreign key not inserted in hibernate
so not able to access employee from access employee_persona_detail
employee table
#OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "employee")
public EmployeePersonalDetail employeePersonalDetail;
#Table(name="employee_personal_details")
#ToString
public class EmployeePersonalDetail {
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employee_id")
private Employee employee;
}
Related
I have a table which has a self reference join table to itself.
#Entity
public class Employee {
#OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<EmployeeDependency> employeeDependencies;
}
#Entity
public class EmployeeDependency {
#ManyToOne
#JoinColumn
private Employee employee;
#ManyToOne
#JoinColumn
private Employee employeeDependency;
}
As we can see the relation is managed by mappedBy = "employee".
DB looks like this for the dependency table
EmployeeDependency
----------------------------------------
id employee_id employee_dependency_id
----------------------------------------
1 2 3
2 2 4
3 3 10
Now when I try deleting employee= 2 , it is deleting the references in EmployeeDependency table and also deleting the record from Employee table as dependency is managed by employee in the mapping mappedBy = "employee". This is expected and working as it is written.
But now when I try to delete employee = 10 which is in other side of relation, I was getting foreign key reference error.
I was able to delete it if I put a dummy reference in Employee entity like this
#Entity
public class Employee {
#OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<EmployeeDependency> employeeDependencies;
#OneToMany(mappedBy = "employeeDependency", cascade = CascadeType.ALL, orphanRemoval = true)
private List<EmployeeDependency> dummyEmployeeDependencies;
}
But this doesn't seems to be right! how can I put a bidirectional cascade so I can delete ids from either side of relation
I have a relation between Accommodation and Booking classes, and also I set a foreign key in booking table.
ALTER TABLE `project`.`booking`
ADD INDEX `fk_accId_fk_idx` (`accommodation` ASC);
ALTER TABLE `project`.`booking`
ADD CONSTRAINT `fk_accId_fk`
FOREIGN KEY (`accommodation`)
REFERENCES `project`.`accommodation` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Accommodation class:
#Entity
....
public class Accommodation implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private BigInteger id;
#OneToMany(mappedBy = "accommodation", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
#JsonManagedReference
private List < Booking > bookings;
......getters setters
}
Booking class:
#Entity
public class Booking implements Serializable {
......
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "bookings", nullable = true)
#JsonBackReference
private Accommodation accommodation;
....getters setters
}
When I execute a query for listing accommodations, I get unknown column in field list error.
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bookings7_.bookings' in 'field list'
Even I set the relation and define the foreign key in table, what is the reason that I get this error?
Try to define your join-table mapping manually in JPA. Drop your schema and let JPA create your tables:
Accommodation class
#OneToMany(mappedBy = "accommodation", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
#JsonManagedReference
private List < Booking > bookings;
Booking class
#ManyToOne(fetch = FetchType.EAGER)
#JoinTable(name = "accommodation_booking_join_table",
joinColumns = {#JoinColumn(name="booking_id")},
inverseJoinColumns = #JoinColumn(name = "accommodation_id"))
#JsonBackReference
private Accommodation accommodation;
Try changing your column names to lower case in your db and entity class.
I had a situation like that, and I solved it by changing the field's position on the query. Looks like it's a MySQL bug, like (or the same as) the one mentioned on this post:
https://bugs.mysql.com/bug.php?id=1689
The description of this MySQL bug mentioned a similar workaround solution: "I found that by swapping that field's position in the table with another field that it worked OK."
I'm have a problem with sql created by Hibernate when I use entity mapped shared primary key. I'm using JPA 2.1 and Hibernate 5.2.2
Here's my entities:
#Entity
#Column(name = "employee_table")
public class EmployeeEntity {
#Id
#Column(name = "id")
#SequenceGenerator
#GeneratedValue
private Long id;
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private EmployeeDetailsEntity employeeDetailsEntity;
}
#Entity
#Table(name = "employee_details")
public class EmployeeDetailsEntity {
#Id
#Column(name = "id")
private Long id;
// additional attributes
}
I want to select all employees which has details:
select e from EmployeeEntity e where e.employeeDetailsEntity is not null;
Select that was generated by Hibernate is:
select employeeen0_.id from employee_table employeeen0_ where employeeen0_.id is not null;
Could you please explaine me what I'm doing wrong and help to solve this?
It looks like you're missing the "other side" of the Employee -> EmployeeDetails relationship mapping:
Employee entity:
private EmployeeDetails employeeDetails;
#OneToOne(mappedBy = "employee", fetch = FetchType.LAZY)
public EmployeeDetails getEmployeeDetails() {
return employeeDetails;
}
EmployeeDetails entity:
private Employee employee;
#OneToOne(optional = false)
#JoinColumn(name = "EMPLOYEE_ID")
public Employee getEmployee() {
return employee;
}
Thanks to all who comments.
The problem is that #PrimaryKeyJoinColumn on EmployeeDetailsEntity using EmployeeEntity primary key and when in your hql you check that EmployeeDetailsEntity in null (or not null) for native sql Hibernate use id of EmployeeEntity because you are shared this PK with another (EmployeeDetailsEntity) entity.
If you don't want (can't) to change you mapping use join in your hql queries or change #OneToOne mapping.
I am learning hibernate and stuck a bit with the below problem
have two tables
CREATE TABLE department (
department_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
caption varchar(255) DEFAULT NULL) ENGINE=InnoDB;
CREATE TABLE employee (
employee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
fio varchar(255) DEFAULT NULL,
fk_department_id int(11) NOT NULL,
FOREIGN KEY (fk_department_id) REFERENCES department (department_id)
) ENGINE=InnoDB ;
and two classes (in the first class commented out code looks like working solution)
#Entity
#Table(name = "department")
public class Department {
....
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "employee", joinColumns = {
#JoinColumn(name = "fk_department_id", referencedColumnName = "department_id") })
/*
* #OneToMany(fetch = FetchType.LAZY, mappedBy = "department", cascade =
* CascadeType.ALL)
*/
public Set<Employee> getEmployies() {
return employees;
}
#Entity
#Table(name = "employee")
public class Employee {
......
#ManyToOne
#JoinColumn(name = "fk_department_id")
public Department getDepartment() {
return department;
}
this results into
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "main" org.hibernate.MappingException: Foreign key (FK3cspe1b06hmsik5l8y1i11xmd:employee [employies_employee_id])) must have same number of columns as the referenced primary key (employee [fk_department_id,employies_employee_id])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:148)
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:130)
Please help me to understand why this doesn't work
The following should work just fine. You'll notice I am not specifying any join column relations because I am allowing Hibernate to generate those automatically for me.
#Entity
public class Department {
#OneToMany
#JoinTable(name = "department_employees")
private List<Employee> employees;
}
#Entity
public class Employee {
#ManyToOne
private Department department;
}
But lets assume you want to be explicit about the join columns.
#Entity
public class Department {
#Id
#Column(name = "department_id")
private Integer id;
#OneToMany
#JoinTable(
name = "department_employees",
joinColumns = #JoinColumn(name = "department_id"),
inverseJoinColumns = #JoinColumn(name = "employee_id"))
private List<Employee> employees;
}
#Entity
public class Employee {
#Id
#Column(name = "employee_id")
private Integer id;
#ManyToOne
#JoinTable(
name = "department_employees",
joinColumns = #JoinColumn(name = "department_id", insertable = false, updatable = false),
inverseJoinColumns = #JoinColumn(name = "employee_id", insertable = false, updatable = false))
private Department department;
}
The key points to take away from this are:
The name of the join table specifies the middle table that maintains the relationship between the Department and Employee entities. It should not refer to the Employee table as your code illustrates.
The joinColumns attribute represents the primary key attributes of the containing entity, in this case that is Department, hence I used department_id.
The inverseColumns attribute represents the primary key attributes of the associated entity, in this case that is Employee, hence I used employee_id.
Update:
If you'd like to eliminate the #JoinTable and merely maintain the relationship between Department and Employee, you'd change your mappings as follows:
#Entity
public class Department {
#OneToMany(mappedBy = "department")
private List<Employee> employees;
}
#Entity
public class Employee {
#ManyToOne
private Department department;
}
Hope that helps.
I am using hibernate 3 and attempting to delete a record in the database, and the delete is not working as I would expect. The schema hibernate is working against (in pseudocode):
create table Employer(
employer_id number(12) primary key,
employer_name varchar2(50)
);
create table Employee(
employee_id number(12) primary key,
employee_name varchar2(50),
employer_id number(12) foreign key references employer.employer_id not null
);
create table Employee_Roles(
role_id number(12) primary key,
employee_id number(12) foreign key references employee.employee_id not null,
role varchar2(50)
);
My hibernate class mappings look something like:
#Entity
public class Employer{
#Id
#Column(name = "EMPLOYER_ID")
private long id;
#Column
private String name;
#OneToMany(targetEntity = Employee.class, fetch = FetchType.EAGER)
#JoinColumn(name = "employer_id")
#Cascade(CascadeType.ALL)
private Set<Employee> employees;
}
#Entity
public class Employee{
#ManyToOne(targetEntity = Employer.class)
#JoinColumn(name = "employer_id")
#Cascade(value = CascadeType.SAVE_UPDATE)
private Employer employer;
#OneToMany(targetEntity = EmployeeRole.class, fetch = FetchType.EAGER)
#JoinColumn(name = "employee_id")
#Cascade(CascadeType.ALL)
private Set<Employee> employees;
}
#Entity
public class EmployeeRole{
#ManyToOne(targetEntity = Employee.class)
#JoinColumn(name = "employee_id")
#Cascade(value = CascadeType.SAVE_UPDATE)
private Employee employee;
}
Now with this configuration I am calling:
getCurrentSession().delete(someEmployerEntity);
What is occurring is:
Hibernate: update EMPLOYEE set EMPLOYEE_ID=null where EMPLOYEE_ID=?
Hibernate: update EMPLOYEE_ROLE set employee_id=null where employee_id==?
[2011-04-15 15:59:53,487] JDBCExceptionReporter WARN - SQL Error: -10, SQLState: 23502
[2011-04-15 15:59:53,487] JDBCExceptionReporter ERROR - integrity constraint violation: NOT NULL check constraint; SYS_CT_10058 table: EMPLOYEE_ROLE
and an exception being raised. What I am expecting as a result of the session.remove(..) call is the employer record to be deleted, as well as all employee records associated with the employer and all EmployeeRole records associated with the deleted employee records. Is this a correct assumption? Or am I misunderstanding a key concept here?
Cascade all-delete-orphan should solve your problem. However, it is part of Hibernate and not EJB standard. If you want to do it and do not be trapped in your vendors' solution, I would suggest you to have a look to this article.
Good luck!
EDIT: following your suggestions I added the 'mappedBy' attributes to the #OneToMany annotations which seems to be the annotations way of using inverse="true" for specifying the owning relationships. The relevant changed sections of the relationships look like:
public class Employee{
#OneToMany(targetEntity = EmployeeRole.class, mappedBy="employee", fetch = FetchType.EAGER, cascadeType=CascadeType.ALL)
private Set<EmployeeRole> employeeRoles;
}
public class Employer{
#OneToMany(targetEntity = Employee.class, mappedBy="employer", fetch = FetchType.EAGER, cascadeType=CascadeType.ALL)
private Set<Employee> employees;
}