0

I am using Java Spring and have a model that I am currently mapping to both a Relational Database (MySQL) and a NoSQL Database (MongoDB).

@Entity
@Document
public class Person {

    @Id
    @AutoGenerated(...)
    private long id;

    @Id
    private String documentId;

    private String firstName;
    private String lastName;

    ...
}

I need the relational model's id to be a long while and the non-relation model to be a String. I am unsure if duplicated '@Id' annotations (even of different types) will cause issues.

Is there a way I can annotate the class to ensure that the model is compatible with JPA and the MongoClient?

Or do I need to create two different classes (PersonDocument, PersonEntity) and convert between the two?

Mike Ryan
  • 4,234
  • 1
  • 19
  • 22
Kevin Chan
  • 21
  • 2
  • check my answer here https://stackoverflow.com/questions/47908365/spring-can-a-class-be-both-document-and-table/47909277#47909277 – pvpkiran May 30 '18 at 14:29

1 Answers1

1

Turns out that it can be done in a single class. So as long as there are no conflicts between the relational / non-relational annotations.

import org.springframework.data.mongodb.core.mapping.Field;

@javax.persistence.Entity
@org.springframework.data.mongodb.core.mapping.Document
public class Person {

    @javax.persistence.Id
    @javax.persistence.GeneratedValue
    @org.springframework.data.annotation.Transient
    private long id;

    @org.springframework.data.annotation.Id
    @javax.persistence.Transient
    private String documentId;

    @Field
    private String firstName;

    @Field
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
Kevin Chan
  • 21
  • 2