3

Can you use both annotations on your database tables?

id, just like some clarification on there differences. thank you

2 Answers2

3

@Entity is used to map a class to a relational database, it represents a database table.

@Document is used to map a class to noSQL database (specifically mongoDB), it represents a MongoDB documents.

You can use both JPA or MongoRepository if you are using both databases by creating different entities and repositories for each database.

I recommend you to have a look at spring documentation (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/)

  • 1
    can we use both the annotations together in a single model class to leverage table/document in a sql and nosql db at the same time? or have to create two different model classes with different annotations. – Sidharth Bajpai Jan 19 '23 at 08:38
  • 1
    Yes, you can use a multi-tenancy approach where you can have a single class annotated with both Entity and Document but with different configurations for different databases. This approach would require a lot of manual work, and it's not recommended unless you have a very specific use case. I would just create different model classes ^^ – Codepressed Jan 19 '23 at 15:51
1

@Document is a Spring Data Mongo annotation while @Entity is part of Java Persistence API (JPA).

You can check both documentations:

Where into "Example 10. Repository definitions using domain classes with annotations" there is this piece of code:

interface PersonRepository extends Repository<Person, Long> { … }

@Entity
class Person { … }

interface UserRepository extends Repository<User, Long> { … }

@Document
class User { … }

And documentation says:

PersonRepository references Person, which is annotated with the JPA @Entity annotation, so this repository clearly belongs to Spring Data JPA. UserRepository references User, which is annotated with Spring Data MongoDB’s @Document annotation.

So you can see here the difference.

J.F.
  • 13,927
  • 9
  • 27
  • 65