JPA Generic Entity using Map - jpa

Is there a way to implement JPA Entity using Map? either extended HashMap or contain a hashmap i.e.:
#Entity
#Table(employee)
public class Employee {
/* .... */
void set(String columnName, Object columnValue) { /*...*/ }
Object get(String columnName) { /*...*/ }
}
and
#RepositoryRestResource
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
this way, there is no need to provide model attributes in the Employee class. Basically, whatever columns are defined in the database, it will be a property like entry in the Employee class.
Employee emp;
...
emp.get("name");
emp.get("id");
Is something like this possible?

Though not possible in vanilla JPA, EclipseLink dynamic entities (https://wiki.eclipse.org/EclipseLink/Examples/JPA/Dynamic) might be what you want. It allows for working with entities in a map-like fashion. Not sure if it is sufficient for your use case, though.

Related

JPA query attribute with a converter

I have a SpringBoot 2.6.11 application with JPA 2.2.
I have an entity like this:
#Data
#Entity
#Table(name = "entity")
public class Entity implements Serializable {
....
#Convert(converter = ListConverter.class)
private List<String> referenceCode;
....
}
I have this Converter:
#Converter(autoApply = true)
public class ListConverter implements AttributeConverter<List<String>, String> {
#Override
public String convertToDatabaseColumn(List<String> attribute) {
return String.join(";", attribute);
}
#Override
public List<String> convertToEntityAttribute(String dbData) {
return new ArrayList<>(Arrays.asList(dbData.split(";")));
}
}
And when I insert or extract this element all working fine. But now I wanna query that element and I don't know how to do it. If I do something like that:
public List<Entity> findByReferenceCode(String reference);
It doesn't work, if I do:
#Query("select e from Entity e where e.referenceCode IN ?1")
public List<Entity> findByReferenceCode(List<String> reference);
Still doesn't work..
The only way I found is by the nativeQuery but is really an extrema ratio. Ho can I solve this?
Thank you
To really do what you want here, you need to use an #ElementCollection. The reason being that there is no reliable way for JPA to query a single column and treat it as a collection. Reliably querying a collection requires a second table (which is what #ElementCollection does). You can continue to use the #Converter, but your queries will have to be customized to handle the disparity between the entity attribute type (list) and the actual database column type (string).
If you are okay with the limitations of the #Converter then it's fine (I have used them this way) but if you truly need to query the attribute like a collection (e.g. search for multiple independent items, perform counts, aggregations, etc) and you want those queries to be generated by a JPA layer, then you will have to use #ElementCollection and let it create a second table.

EAGER loading with one select doesn't work in Spring Data JPA

there is already a similar post. Since this is already older, I hope something has changed since then (How does the FetchMode work in Spring Data JPA)
I would like to run all jpa repository#findById in one select, if the relationship is marked with EAGER. However, spring data ignores the EAGER specification and the FETCH.JOIN annotation from hibernate.
Is there a generic solution that all findById queries are executed in one select?
I wouldn't want to write a separate JPL or EntityGraph for each query. Does anyone know a generic solution?
JpaReposistory
The easiest option would be to write a JpaRepository<T, Id>. This is still a custom repository. However, you do not have to write so much code. You mainly have to write a repository interface for each relevant class and annotate the findById(Long id) method with a graph. The advantage is that if you edit your entity, the repository method will not need any changes because you define the entity graph within the entity class itself.
#Entity
#NamedEntityGraph(name = "Department.detail",
attributeNodes = #NamedAttributeNode("employees"))
public class Department {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(fetch = FetchType.LAZY)
private List<Employee> employees;
// ...
}
public interface DepartmentRepository extends JpaRepository<Department, Long> {
#EntityGraph(value = "Department.detail", type = EntityGraphType.LOAD)
List<Department> findById(Long id);
}
As Spring data ignores the #Fetch(Fetchmode.JOIN) annotation or the information fetch = FetchType.EAGER, you cannot influence the join how you want it to be within the entity itself.
JPQL Query Where You Need It
Another option can be considered as a bad software engineering style: You can call the database queries directly where you need them. This means that you execute the code which you would usually write in the repository.
public ClassWithQueryResults {
#PersistenceContext
private EntityManager entityManager;
public void methodWhereYouNeedYourResults() {
TypedQuery<Department> query = entityManager.createQuery(
"SELECT DISTINCT d FROM Department d LEFT JOIN d.employees e",
Department.class);
List<Department> departments = query.getResultList();
// ...
}
}
Repository With JPQL, Generics and Reflection
Taking the previously suggested idea, you can create a custom repository which is valid for all your entities. The first step would be to create an attribute in your entity class in which you store the attribute which should be fetched.
public class Department extends AbstractEntity {
public static void String ATTRIBUTE_TO_FETCH = "employees";
...
}
With some tweaking, this can be extended to an array/list of all the fields which should be fetched. As this attribute is directly in your entity classes, the chance for any mistakes and future effort is low. Obviously, this attribute should have the same name in all your entities.
The next step would be to create the repository. I provide an example with the findAll() method. You have to pass it only the class name of the entities you want to have and the generics and reflection do the rest. (Consider what you want to do with the exceptions.)
public <T> List<T> findAll(Class<T> tClass)
throws NoSuchFieldException, IllegalAccessException {
String className = tClass.getSimpleName();
String attributeToFetch = (String)
tClass.getDeclaredField("ATTRIBUTE_TO_FETCH").get(null);
String queryString = String.format("SELECT DISTINCT p FROM %s p LEFT JOIN p.%s c",
className, attributeToFetch);
TypedQuery<T> query = entityManager.createQuery(queryString, tClass);
return query.getResultList();
}
Depending on how you want to implement this, the modification/generation of a query through simple manipulation of a String can offer the possibility of SQL injection attacks.

Entity Framework code first Inheritance Issue

I have code first implementation for flowing hierarchy,
BaseContact{
Public int Id{get;set;}
public string Name{get;set;}
//..
}
Person:BaseContact{
public string Designation{get;set;}
//..
}
Company:BaseContact{
public int NumOfEmployees{get;set;}
//..
}
I want to identify person or company with by using only the Id value? Currently I am using reflection to identify whether it is a person or company. Is there any other way to identify it without doing too much?
Without seeing how you initialised your classes I'm going to assume you have a table per concrete type approach.
You can't do it just from the ID, as you don't know which table the ID belongs to. ID 2 in "Person" table is a different entity to ID 3 in "Company". The only practical way to identify only from an ID is using a Table per Hierarchy approach and inspecting the type descriptor.
Some good references
http://weblogs.asp.net/manavi/archive/2011/01/03/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines.aspx
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
You can also use a simple is statement instead of reflection. Ie if (entity is Company)
In your BaseContact (assume it is an abstract class) add abstract property which will be implemented by other two classes.Use Enum to identify the property type as follows.
public enum MyType
{
Person,
Company,
};
public abstract class BaseContact{
public abstract MyType ContactType{get;}
}
public class Person:BaseContact
{
public override MyType ContactType
{
get
{
return MyType.Person;
}
}
}
public class Company:BaseContact
{
public override MyType ContactType
{
get
{
return MyType.Company;
}
}
}
Use your BaseContact repository to retrieve entities and use enum for type separation.

Entity framework code first creates "discriminator" column

I am using EF CF approach for a website with MySQL.
For some reason EF creates a column in my Post table called "Discriminator" and contains the VARCHAR "Post".
Why is this column created? Can I do something to avoid it being created? Are there any advantages of having this column?
The Discriminator column is used and required in Table-Per-Hierarchy inheritance scenarios. If you for example have a model like this ...
public abstract class BaseEntity
{
public int Id { get; set; }
//...
}
public class Post : BaseEntity
{
//...
}
public class OtherEntity : BaseEntity
{
//...
}
... and make the BaseEntity part of the model, for instance by adding a DbSet<BaseEntity> to your derived context, Entity Framework will map this class hierarchy by default into a single table, but introduce a special column - the Discriminator - to distinguish between the different types (Post or OtherEntity) stored in this table. This column gets populated with the name of the type (again Post or OtherEntity).
You can stop the column being created by adding the [NotMapped] data annotation to the models that are inheriting from your base class. This will tell EF not to add your class to future migrations, removing the discriminator column.
public class BaseClass
{
}
[NotMapped]
public class InheritingClass : BaseClass
{
}
For completeness, if you want to use the fluent API to stop the inheriting class from being mapped with entity (and therefore stopping the discriminator column being created) you can do the following:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Ignore<InheritingClass>();
}

EF CTP5 POCO, base class and how to implement inheritance

Hey,
lets say I want all my recordsto have a standard stamp on them.
inserted_by, inserted_at, updated_by, updated_at, deleted_by, deleted_at, timestamp
1 - If I had to put this in a base (maybe abstract) POCO class, what would be the best inheritance strategy to implement this. (I am using GUID as primary keys.)
I do not want to use base class for anything else.
In my Db Context;
I'd like to use the end POCO classes that corresponds to the db table.
DbSet, looks like I have to use DbSet tough, then use OfType to query:)
2 - If Inheritance is out of context, what would you recommend, ComplexType, an Interface maybe?
I do exactly that in EF4. There is a generic repository base class:
public class GenericRepository<T> : IGenericRepository<T> where T : BaseEntity
All entity repositories inherit from this class. The generic .Add() and .Update() method automatically set the audit data:
public void Add(T entity)
{
entity.CreatedOn = DateTime.UtcNow;
entity.CreatedBy = UserName;
entity.LastModifiedOn = entity.CreatedOn;
entity.LastModifiedBy = entity.CreatedBy;
ObjectContext.AddObject(GetEntitySetName<T>(), entity);
}
public void Update(T entity)
{
T originalEntity = ObjectSet.Single(t => t.Id == entity.Id);
entity.CreatedOn = originalEntity.CreatedOn;
entity.CreatedBy = originalEntity.CreatedBy;
entity.LastModifiedOn = DateTime.UtcNow;
entity.LastModifiedBy = UserName;
ObjectSet.ApplyCurrentValues(entity);
}
So you can see that it doesnt go into the POCO base class BaseEntity, because it's not the responsibility of the POCO. Instead it belongs to the Repository.
You need TPC inheritance (Table per class or Table per concrete type). Check this article about CTP5 mapping of TPC.