Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Annotations & ORM.xml alternative?

I want to design my Microservice in a way i can change Frameworks as easy as possible. So i have an Interface for everything that could change in the future, but I can't do that for Entities because I'm not aware of a way of using JPA + Hibernate without using @Entity / @Id.. or declaring a ORM.xml File. Is there maybe a way to define configuration class(es) which handle Entities?

Random-Example:

@Entity 
@IdClass(DemoId.class)
@Table(name = "demo",catalog="demodb")
public class Demo implements Serializable{
    @Id
    private long pk1;
    @Id
    private long pk2;
    @Id
    private long pk3;    
    @Lob
    String description; 

    @ElementCollection(targetClass=String.class)
    List<String> infos = new ArrayList<>(); 
}

public class DemoId implements Serializable{   
    private long pk1;
    private long pk2;
    private long pk3;    
}

How could I separate my Entities (in this case Demo) and the JPA-Annotations in two Classes? So if there ever would be something that makes JPA Deprecated I could easy switch (and just change 1 adapter or something like that)

Ty in advanced

like image 843
backup backup Avatar asked Jul 13 '26 11:07

backup backup


1 Answers

From my understanding and experience with JPA, it's impossible to have the best of both worlds with this issue. The JPA relies on the Annotations directly inside the file. The best alternative you have as I see it, is to create two separate .java files for each. It's not a pretty solution but I don't think you'll get anything better.

ex: File #1 DemoAnnotated.java

@Entity 
@IdClass(DemoId.class)
@Table(name = "demo",catalog="demodb")
public class Demo implements Serializable{
    @Id
    private long pk1;
    @Id
    private long pk2;
    @Id
    private long pk3;    
    @Lob
    String description; 

    @ElementCollection(targetClass=String.class)
    List<String> infos = new ArrayList<>(); 
}

File #2 Demo.java

public class Demo implements Serializable{
    private long pk1;
    private long pk2;
    private long pk3;    
    String description; 
    List<String> infos = new ArrayList<>(); 
}

You'll probably save time in the long run to just keep the annotations for now. If you need to quickly switch over frameworks later on - it will require refactoring but you should be able to do it rather quickly. I can't imagine the changes being too intense. Might simply be a @Entity -> @SomeOtherName which in that case you can do a search and replace. Search and replace might be your saviour here.

like image 147
BallsBot Avatar answered Jul 16 '26 00:07

BallsBot