I am writing an application that I wish to follow the DDD patterns, a typical entity class looks like this:
@Entity
@Table(name = "mydomain_persons")
class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name="fullname")
private String fullName;
@OneToMany(cascade=ALL, mappedBy="item")
private Set<Item> items;
}
As you see, since the JPA/Hibernate heavily relies on annotations on entity classes, my domain entity classes are now polluted by persistence-aware annotations. This violates DDD principles, as well as separation of layers. Also it gives me problems with properties unrelated to ORM, such as events. If I use @Transient, it will not initialize a List of events and I have to do this manually or get weird errors.
Id like the domain entity to be a POJO(or POKO as I use Kotlin), so I do not want to have such annotations on the entity class. However I definitely do not wish to use XML configurations, its a horror and the reason why Spring developers moved on to annotations in the first place.
What are the options I have available? Should I define a DTO class that contains such annotations and a Mapper class that converts each DTO into the corresponding Domain Entity? Is this a good practice?
Edit: I know in C# the Entity Framework allows creation of mapping classes outside of Entity classes with Configuration classes, which is a way better alternative than XML hell. I aint sure such technique is available in the JVM world or not, anyone knows the below code can be done with Spring or not?
public class PersonDbContext: DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Write Fluent API configurations here
//Property Configurations
modelBuilder.Entity<Person>().Property(p => p.id).HasColumnName("id").IsRequired();
modelBuilder.Entity<Person>().Property(p => p.name).hasColumnName("fullname").IsRequired();
modelBuilder.Entity<Person>().HasMany<Item>(p => p.items).WithOne(i => i.owner).HasForeignKey(i => i.ownerid)
}