How to override parent #MappedSuperclass #column attributes in child entity extending parent while inserting child entity - entity

I have two classes A & B, B extends A and A is #MappedSuperclass as it is extended by other entities as well for some common fields.
Class A
#MappedSuperclass
public class A implements Serializable {
#Column(name="TYPE_ID")
private String type;
#Column(name="FEATURE_CODE")
private String featureCode;
}
Class B
public class B extends A implements Serializable {
#Column(name="ID")
private String id;
#Column(name="GROUP")
private String group;
}
Now the problem is while I'm trying to persist class B it takes TYPE_ID and FEATURE_CODE into the INSERT query and the target database table TABLE B doesn't have the column FEATURE_CODE which results in exception.
Can anyone point me in the right direction on how to ignore the FEATURE_CODE field while persisting the child entity B?
Thanks !

#MappedSuperclass needs a constructor and its get and set. and your class, B,..
must have the columns of A in the database, if you do it with hibernate you should create them automatically, but if you do it manually, you must create the columns of A in the table of B

Related

Create object of one type from object of another type with database lookups

I have an application that gets a car entity from a third party database. I call the entity ThirdPartyCar. My application needs to create a Car entity by using data from a ThirdPartyCar. However, the Car entity must also derive some of its data from my application's database. For example, a status of a ThirdPartyCar might be _BOUGHT and through a database lookup my application must transform to Sold.
I currently have a Car constructor that has a ThirdPartyCar argument. But the Car constructor cannot populate the lookup data since it is an entity and entities should not have a reference to a repositories. So, I also have a service to populate the remaining data:
public class ThirdPartyCar {
#Id
private Long id;
private String vin;
private String status;
// more props + default constructor
}
public class Car {
#Id
private Long id;
private String vin;
private CarStatus status;
// more props (some different than ThirdPartyCar) + default constructor
public Car(ThirdPartyCar thirdPartyCar) {
this.vin = thirdPartyCar.getVin();
// more props set based on thirdPartyCar
// but props leveraging database not set here
}
public class CarStatus {
#Id
private Long id;
private String status;
}
public class CarBuilderService {
private final CarStatusMappingRepository repo;
public Car buildFrom(ThirdPartyCar thirdPartyCar) {
Car car = new Car(thirdPartyCar);
CarStatus status = repo.findByThirdPartyCarStatus(thirdPartyCar.getStatus());
car.setStatus(status);
// set other props (including nested props) that depend on repos
}
}
The logical place to create a Car based on a ThirdPartyCar seems to be the constructor. But I have a disjointed approach b/c of the need of a repo. What pattern can I apply such that all data is created in the constructor but still not have the entity be aware of repositories?
You should avoid linking two POJO classes from different domains in constructor. These two classes should not know anything about each other. Maybe they represent the same concept in two different systems but they are not the same.
Good approach is creating Abstract Factory interface which will be used everywhere where Car should be created from ThirdPartyCar:
interface ThirdPartyCarFactory {
Car createNewBasedOn(ThirdPartyCar source);
}
and one implementation could be your RepositoryThirdPartyCarFactory:
class RepositoryThirdPartyCarFactory implements ThirdPartyCarFactory {
private CarStatusMappingRepository repo;
private CarMapper carMapper;
public Car createNewBasedOn(ThirdPartyCar thirdPartyCar) {
Car car = new Car();
carMapper.map(thirdPartyCar, car);
CarStatus status = repo.findByThirdPartyCarStatus(thirdPartyCar.getStatus());
car.setStatus(status);
// set other props (including nested props) that depend on repos
return car;
}
}
In above implementation you can find CarMapper which knows how to map ThirdPartyCar to Car. To implement this mapper you can use Dozer, Orika, MapStruct or your custom implementation.
Other question is how you got ThirdPartyCar object. If you load it by ID from ThirdPartyRepository you can change your abstract factory to:
interface CarFactory {
Car createNew(String id);
}
and given implementation loads by ID ThirdPartyCar and maps it to Car. Everything is hidden by factory which you can easily exchanged.
See also:
Performance of Java Mapping Frameworks

LINQ Parent class queries db for fields in child class

I'm using EF 6.1.3 and .NET framework 4.5.2
I'm updating code which uses two classes:
Public Class Holder
<Key(), Column(Order:=0)>
Property Holder_No As Integer?
<Key(), Column(Order:=1)>
Property Title_No As Integer?
Property Family_Name As String
Property Given_Name_1 As String
Property Given_Name_2 As String
End Class
Public Class OwnerChange
Inherits Holder
Public Property Change_Type As String
Public Property Change_Date As Date
Public Property Process_Date As Date?
End Class
The Holder class is a 1:1 mapping with a table in the db.
The DbContext only creates a dbSet for the Holder class.
Public Property Holder As DbSet(Of Holder)
When I create a simple query to access data from the holder table in the db, I get column errors for change_type, change_date and process_date.
Using contextdb = New userContext()
Dim att1 = (From b In contextdb.Holder
Select b).Take(10)
End Using
The query seems to think I'm trying to query the parent table for the child class' information.
Why does LINQ request the child's columns from the parent class' table in the database? Do I need to do something to specify that I only want to retrieve the holder information?
The Entity Framework apparently creates a hierarchy whenever one class is inherited from another. So, when I was querying for the holder record, it was looking in the holder table for the elements from the OwnerChange class.
What I needed to do was take the holder class and turn it into an abstract class, then inherit it into the two classes I want to access different tables in the database.
Public MustInherit Class base_class
<Key(), Column(Order:=0)>
Property Holder_No As Integer?
<Key(), Column(Order:=1)>
Property Title_No As Integer?
Property Family_Name As String
Property Given_Name_1 As String
Property Given_Name_2 As String
End Class
Public Class OwnerChange
Inherits base_class
Public Property Change_Type As String
Public Property Change_Date As Date
Public Property Process_Date As Date?
End Class
Public Class holder
Inherits base_class
End Class
Changing the class hierarchy ultimately solved the problem.

Recommended strategy to use Value Objects for ID's in Spring Data

Using Value Objects can have a lot of advantages, especially when it comes to the type strictness of it. Using a PersonKey to use a Person (where the PersonKey really is a wrapped Long) is a lot safer than just using a Long or String as-is. I was wondering what the recommended strategy to deal with this in Spring Data is, however. Setting up the Repository is of course a matter of for example using
public interface PersonRepository CrudRepository<Person, PersonKey> {
}
but I was wondering what the best way to make the PersonKey class would be, having it map easily. Is there a better option than using an EmbeddedKey?
There is two annotations to do it : IdClass or EmbeddedId. I would recommend to use EmbeddedId because you don't have to repeat all of your attributes of your id class into your entity class.
Let's say you use EmbeddedId. It would looks like this :
#Embeddable
public class PersonKey {
private Long id;
}
#Entity
public class Person {
#EmbeddedId
private PersonKey personKey;
}
And you will access to your id like this :
select p.personKey.id from Person p
But with IdClass, your Person class would look like this :
#Entity
#IdClass(Person.key)
public class Person {
#Id
private Long id;
}
And you will access like this :
select p.id from Person p

Hibernate inheritance without table for basic entity

I've never used inheritance in hibernate and I don't know which strategy should I use (or even do I really need to use strategy). I have three tables with the same interface (the same columns) and I want to create three entities with basic interface for them so it will look like this:
#Entity
+ Basic
+ #Entity
#Table(name="TABLE_1")
Table1
+ #Entity
#Table(name="TABLE_2")
Table2
+ #Entity
#Table(name="TABLE_3")
Table3
As you see I don't want to use table for basic entity. If it is possible to do this kind of inheritance, how to do it? Maybe I don't need 'hibernate' inheritance and I should use normal inheritance?
In application it is used like this:
Somewhere in configuration we store information which entity to use (Table1, Table12 or Table3)
Choosen entity is used in our queries (some writen in HQL, some in Criteria) so each query should know which entity to use.
EDIT
What's more each entity can be used as attribute of some entities and we wan't to know which table should be used. For example:
#Entity
#Table(name="USER")
class User {
#Id
private Integer id;
#ManyToOne
#JoinColumn(name = "SOME_ID", referencedColumnName = "ID", nullable = false)
private Basic basicEntity; // how to use proper strategy using some configuration value (eg. class static attribute or configuration value stored in db?)
}
I think this is recommended way of achieving your goal:
#MappedSuperclass
public abstract class BaseEntity {
public static final int SHARED_PAREMETER = 2;
#Column(name = "modified", columnDefinition = "TIMESTAMP DEFAULT NOW()")
protected Date modified;
//... other fields, getters and setters
}
#Entity
#Table(name = "TABLE_1")
public class Table1 {
#Id
private Integer id;
#ManyToOne
#JoinColumn(name = "SOME_ID", referencedColumnName = "ID", nullable = false)
private Table2 table2;
}
#Entity
#Table(name = "TABLE_2")
public class Table2 {
#Id
private Integer id;
}
In this case, we will have only two tables but both would have fields from BaseEntity. You can't, though, make a relation in Entity to an abstract class but in processing you're fully entitled to do something like this:
public void process(BaseEntity entity){
// processing..
}

Mapping a referenced base class with fluent nhibernate

I am trying to map a class hierarchy which looks like this:
public abstract class A { }
public class B : A { }
public class C : A { }
I don't want to map class A because it is abstract, I know I can do:
.IgnoreBase<A>()
to not map A and map all properties of A in B and C. But my problem is that I also have another class D which looks like following:
public class D {
public virtual A a { get; set; }
}
Now, when I try to map with fluent nhibernate auto mapping feature I get an error that class D refers to an unmapped class A, though class A is actually mapped through subclasses B and C.
Anyone know how to solve this?
If you don't map class A the classes B and C won't be subclasses. They are just two classes that are not connected at all. NHibernate knows nothing about class A, so how should NHibernate know how to handle references to class A?
Not mapping A because it's abstract is no reason. You can map interfaces too.
Maybe it would be more clear what you want to do if you show us your DB model (tables).