Creating an instance of Entity in Spring without any Spring interaction

Sayak Mukhopadhyay :

In my project based on spring-data-rest I have some classes annotated with the @Entity annotation.

@Entity
@Table(name = "my_table)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class MyTable extends BaseTableEntity {
    private String name;
    private String description;
}

Now I am not quite sure as to how Spring handles creation of new instances of classes annotated with that annotation. I needed to create an object of such an Entity class making sure that no database operations takes place.

To make it clear, say I do MyTable table = new MyTable() in a POJO class. Can I be sure that Spring with the help of Hibernate/JPA won't create records in my database. What if I do the same in a @Component class instead of a POJO.

Andronicus :

Creating a new entity with new keyword does not make any insert into db. The entity is in detached state. You would have to pass this entity to reporitory.save or entityManager.persist or entityManager.merge... But as long persist is not invoked (directly or indirectly), it's a regular pojo without a representation in database.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143084&siteId=1