JPA 2.0: однонаправленное каскадное удаление OneToMany с составным первичным ключом - PullRequest
0 голосов
/ 19 июня 2019

Я создал две сущности, которые имеют отношение один-ко-многим, и мне приходится удалять дочерние записи при удалении родительской записи.

//following entities

@IdClass(EmployeeKeys.class)
@Entity
@Table(name="SHAEM_EMPTBL")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee {

@Id
@Column(name="CLIENTID")    
private String clientid;

@Id
@Column(name="EMPID")   
private String empid;


@Column(name="EMPNAME") 
private String empname;

@Column(name="DOJ") 
private Date doj;

@OneToMany(cascade = {CascadeType.ALL},fetch = 
FetchType.LAZY,orphanRemoval 
= true)
@JoinColumns(
    {@JoinColumn(name = "CLIENTID", referencedColumnName = "CLIENTID"),
        @JoinColumn(name = "EMPID",referencedColumnName = "EMPID"),

    })
private List<EmployeeSmry> employeesmry;

@Column(name="ISACTIVE")    
private String isactive;

@Column(name="SYSTEMACCESS")    
private String systemaccess;

//setters and getters
}



@IdClass(EmployeeSmryKeys.class)
@Entity
@Table(name="SHAEM_EMPSMRY")
@JsonIgnoreProperties(ignoreUnknown = true)
public class EmployeeSmry implements Serializable{

@Id
@Column(name="CLIENTID")    
private String clientid;

@Id
@Column(name="EMPID")   
private String empid;

@Id
@Column(name="EFFDT")
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy")
private Date effdt;


@Column(name="STATUS")  
private String status;

@Column(name="DESIGNATION") 
private String designation;

@Column(name="DEPARTMENT")  
private String department;

//setters and getters

}


//delete code that i have tried
public void deleteEmployee(Employee employee) 
{

EntityManager em = emf.createEntityManager();
 em.getTransaction().begin();
 Employee employees = new  Employee();
 employees.setClientid(employee.getClientid());
 employees.setEmpid(employee.getEmpid());
 employees.setDoj(employee.getDoj());
 employees.setEmployeesmry(null);
 Object id = em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(employees);
 Object obj = em.find(employees.getClass(), id);
 System.out.println("===============obj=============="+obj);
 em.remove(obj);
 em.getTransaction().commit();
 em.close();
 }  


             //below queries are hitting 
             the data base

            Hibernate: select employee0_.CLIENTID as CLIENTID1_6_0_, 
            employee0_.EMPID as EMPID2_6_0_, employee0_.ADDR1 as 
            ADDR3_6_0_, employee0_.ADDR2 as ADDR4_6_0_, employee0_.CITY as 
            CITY5_6_0_,  employee0_.DOJ as DOJ11_6_0_, 
            employee0_.DYNAFLD01 as DYNAFLD12_6_0_,_.EMPNAME as 
            EMPNAME15_6_0_, employee0_.ISACTIVE as ISACTIV16_6_0_, 
            employee0_.SYSTEMACCESS as SYSTEMA22_6_0_,  from SHAEM_EMPTBL 
            employee0_ where employee0_.CLIENTID=? and employee0_.EMPID=?




            Hibernate: select employeesm0_.CLIENTID as CLIENTID1_5_0_, 
            employeesm0_.EMPID as EMPID3_5_0_, employeesm0_.EFFDT as 
            EFFDT2_5_0_, employeesm0_.CLIENTID as CLIENTID1_5_1_, 
            employeesm0_.EFFDT as EFFDT2_5_1_, employeesm0_.EMPID as 
            EMPID3_5_1_, employeesm0_.COMMENTS as COMMENTS4_5_1_, 
            employeesm0_.CREATEDBY as CREATEDB5_5_1_, 
            employeesm0_.CREATEDON as CREATEDO6_5_1_, 
            employeesm0_.DEPARTMENT as DEPARTME7_5_1_,from SHAEM_EMPSMRY 
            employeesm0_ where employeesm0_.CLIENTID=? and 
            employeesm0_.EMPID=?


           Hibernate: update SHAEM_EMPSMRY set CLIENTID=null, EMPID=null 
           where CLIENTID=? and EMPID=?

Я ожидаю удаления записей сотрудников и сотрудников, но получаю следующее исключение

2019-06-19 19: 36: 01.187 ПРЕДУПРЕЖДЕНИЕ 5384 ---[nio-8080-exec-4] ohengine.jdbc.spi.SqlExceptionHelper: Ошибка SQL: 515, SQLState: 230002019-06-19 19: 36: 01.187 ОШИБКА 5384 --- [nio- 8080-exec-4]

ohengine.jdbc.spi.SqlExceptionHelper: Невозможно вставить значение NULL в столбец 'CLIENTID', таблица 'Table_Name';столбец не допускает пустых значений.ОБНОВЛЕНИЕ завершается ошибкой.

2019-06-19 19: 36: 01.188 ИНФОРМАЦИЯ 5384 --- [nio-8080-exec-4] ohejbinternal.AbstractBatchImpl: HHH000010: При выпуске пакета оно все еще содержало операторы JDBC 2019-06-19 19: 36: 01.193 ОШИБКА 5384 --- [nio-8080-exec-4] ohiExceptionMapperStandardImpl: HHH000346: Ошибка во время управляемого сброса [org.hibernate.exception.ConstraintViolationException: не удалось выполнить оператор] javax.persistence.RollbackException:Ошибка при фиксации транзакции в org.hibernate.internal.ExceptionConverterImpl.convertCommitException (ExceptionConverterImpl.java:81) в org.hibernate.engine.transaction.internal.TransactionImpl.commit (TransactionImpl.java:107)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...