Search code examples
javasqljpajdbchsqldb

what is the hsql/jdbc equivalent to JPA Detach api? what does it exactly do?


I'm migrating JPA api detach to plain SQL using JDBC, where iam finding it hard to understand the concept of EntityManager.detach(someTask).

I tried using a delete query for detach but it seems to remove the whole record at once from the DB.

@Entity
@Table(name = "TASK", indexes = {@Index(name = "RIO", columnList = "priority", unique = false),
@Index(name = "EXP", columnList = "expiry", unique = false), 
@Index(name = "STA", columnList = "taskStatus", unique = false),
@Index(name = "CAT", columnList = "category", unique = false),
@Index(name = "NEXTTRY", columnList = "nextTry", unique = false)})

public class TaskEntity {

@Version
private int version;

@Basic
@Column(length = Integer.MAX_VALUE, columnDefinition = "varchar(" + 
Integer.MAX_VALUE + ")")
private String taskId;

@Basic
private String category;

@ElementCollection(fetch = FetchType.EAGER)
@MapKeyColumn(name = "KEY")
@CollectionTable(name = "TASKPROPERTIES", foreignKey = @ForeignKey(
             name = "TASK_ID_FK",
             foreignKeyDefinition = "FOREIGN KEY (TASKENTITY_ID) REFERENCES TASK (ID) ON DELETE CASCADE"))

@Column(length = Integer.MAX_VALUE, columnDefinition = "varchar(" + 
Integer.MAX_VALUE + ")")
private Map<String, String> TaskProperties;

@Basic
@Column(length = Integer.MAX_VALUE, columnDefinition = "varchar(" + 
Integer.MAX_VALUE + ")")
private String destination;

@Enumerated(EnumType.STRING)
private TaskStatus taskStatus;

@Basic
private String type;

@Basic
private Long expiry;

@Basic
private Long nextTry;

@Basic
private Integer retries;

@Basic
private Integer priority;

//Setters and Getters
//Equals and HashCode

}

Finding it hard to understand the difference between detach and remove.So what would be the equivalent query of detach in HSQL/SQL?


Solution

  • In order to understand detach you must first familiarize yourself with the proxy design pattern. When you persist or fetch entities, the ORM gives you a proxy which tracks field modifications and gives you lazy loading for instance.

    When you detach an entity you tell the ORM that you do not want it to track that object instance any more. So any changes you made to the entity instance after detaching it, will not be reflected in the database.

    In other words detach() is purely a functionality of the ORM and is not related to the database, that's why you cannot find and SQL equivalent - simply because there is none.