2

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.

12
  • remove @Table and make sure you have not allowed creation of table in properties file Commented Apr 16, 2019 at 17:55
  • Short answer: yes you can be sure. Commented Apr 16, 2019 at 17:55
  • @SyedMehtabHassan Could you elaborate a bit? I have the @Table annotation since I want to manage automatic table creation for these entities. Its just that sometimes I want to create a POJO from the same annotated class without bothering about the database. Commented Apr 16, 2019 at 17:58
  • @Andronicus So, I can be sure that unless I do MyTableRepository.save(table), the table object won't be monitored by Spring for updates and stuff. Commented Apr 16, 2019 at 18:00
  • @SayakMukhopadhyay yes, see my answer;) Commented Apr 16, 2019 at 18:00

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And what in case of load data?
What do you mean? If you load something from database, you need to call entityManager.detach(entity);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.