How is entities inheritance implemented in Spring data mongodb - mongodb

I've two entities Person, Employee and Employee1. I want to implement entities inheritance in Spring Data MongoDB. Like in Spring Data JPA, what are the equivalent annotations for #Inheritance and #PrimaryKeyJoinColumn in Spring Data MongoDB. Right now, I've implemented something like this:
interface Person {
String getId();
void setId(String id);
String getName();
void getName(String name);
}
#Document(collection = "person")
class PersonImpl implements Person {
#Id
String id;
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
interface Employee extends Person {
int getNumberOfDependents();
void getNumberOfDependents(int numberOfDependents);
}
#Document(collection = "employee")
class EmployeeImpl extends PersonImpl implements Employee {
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
interface Employee1 extends Person {
int getNumberOfDependents();
void getNumberOfDependents(int numberOfDependents);
}
#Document(collection = "employee1")
class Employee1Impl extends PersonImpl implements Employee1 {
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
Repository structure:
public interface PersonRepository extends MongoRepository<Person, String> {
}
public interface EmployeeRepository extends MongoRepository<Employee, String> {
}
public interface Employee1Repository extends MongoRepository<Employee1, String> {
}
I'm saving the Person object first and then taking the ID of it and creating an Employee object with the same ID and saving it. This creates new object and hence I'm losing all the Person object stuff.
I also feel that I've to get the NoRepositoryBean implemented also.
I'm confused. Please help.

Here is one approach:
#Document(collection = "person")
class Person {
#Id
String id;
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
Note that the collection field refers to "person" and not to "employee"
#Document(collection = "person")
class Employee extends Person {
String jobTitle;
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
In this method you do not need to create a repository for each derived class
#Repository
public interface PersonRepository extends MongoRepository<Person, String> {}
Code example:
#Autowired
private PersonRepository personRepo;
public void test() {
Employee employee = new Employee("1", "teacher")
personRepo.save(employee)
Optional<Person> optionalPerson = personRepo.findById("1");
Employee employeeFromDb;
if (optionalPerson.isPresent()) {
employeeFromDb = (Employee)optionalPerson.get()
}
else {
// could not find in db
}
}

if you want to find all employees you should have a methode on MongoRepository
called
List<Employee> findAll();

Related

MapStruct equivalent of hint(Dozer)?

In Dozer we are able to mention interfaces in hint during field mapping. How can we achieve the same in MapStruct ?
I could not put the exact code here. But, it is the similar as below.
We have here an Domain class example:
Class A<T extends B> extends C<T>
{
...
};
Where,
B is a abstract class.
C is a class which contains a List item which we have to map.
Similar is the structure of the classes and interfaces on DTO side.
So, the mapping is as below in Dozer:
<mapping>
<class-a>Domain.A</class-a>
<class-b>DTO.A</class-b>
<field>
<a>item</a>
<b>item</b>
<a-hint>Domain.B</a-hint>
<b-hint>DTO.B</b-hint>
</field>
</mapping>
In MapStruct how do we refer the interfaces as given in the hint in Dozer ?
Scenario:
We have:
public class ShopList<T extends Inp> extends Shop<T>\
{ ... };
where,
Inp is a abstract class with no fields in it like:
public abstract class Inp() { };
Shop is a class like:
public class Shop<T extends ShopInp> implements Serializbale
{ private List<T> items = new ArrayList<T>();
//getters and setters for the items };
ShopInp is a public interface with no fields in it like:
public interface ShopInp {} .
We have similar structure of classes on DTO side and Domain side.
Could you please let me know how would the mapper look like for the above scenario ?
In general, If we try mapping the ShopList class, then, how do we ensure that the T extends ShopInp and T extends Inp are also being mapped as a part of ShopList?
So called hints can be used via BeanMapping#resultType. MapStruct can use that to create the instance of the object you are trying to map. However, it will only create mapping for the elements of the abstract class, as it has no other information during compilation time (Dozer uses reflection and can detect the fields of the type during runtime).
Imagine you have this structure
public interface Fruit {
String getName();
String setName(String name);
}
public Apple implements Fruit {
...
}
public Banana implements Fruit {
...
}
public abstract class FruitDto {
private String name;
//getters and setters
}
public AppleDto extends FruitDto {
...
}
public BananaDto extends FruitDto {
...
}
public class Basket {
private Collection<Fruit> fruits;
}
public class BasketDto {
private Collection<FruitDto> fruits;
}
Your mapper can then look like:
#Mapper
public interface BasketMapper {
BasketDto map(Basket basket);
#BeanMapping(resultType = BananaDto.class)
FruitDto map(Fruit fruit);
}
Using this mapper all fruits in the BasketDto would be of an instance BananaDto (due to the BeanMapping#resultType and mapping would only be created for the elements of the FruitDto

Json custom deserializer not called in Websphere

I have simple class and field id is annotated with custom deserializer.
public class TestRequest implements Serializable {
#NotNull
#Pattern(regexp = "^[a-zA-Z0-9=+]*$")
#JsonDeserialize(using = StringDeserializer.class)
#JsonProperty
private String id;
//getter
//setter
}
and the custom deserializer class :
public class StringDeserializer extends JsonDeserializer<String> {
#Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) {
Iterator<String> iterator = jsonParser.readValuesAs(String.class);
String id = iterator.next();
return id + "0000";
}
}
When i test with with Jersey REST test, the deserilizer is called and works as expected. But with websphere it does not called. Any idea why its not called.
I am using jaxrs 1.1
You may need to add the #Provider annotation to your StringDeserializer class, otherwise the JAX-RS runtime will not recognize the class as a provdier.
Even though your class extends JsonDeserializer<String>, which itself is probably annotated with #Provider, the JAX-RS runtime will not scan libraries for annotations, as doing negatively impacts performance.
I made it working in Websphere by moving the annotation #JsonDeserialize(using = StringDeserializer.class) to setter method of the class
public class TestRequest implements Serializable {
#NotNull
#Pattern(regexp = "^[a-zA-Z0-9=+]*$")
#JsonProperty
private String id;
#JsonDeserialize(using = StringDeserializer.class)
public setId(String id){
this.id=id;
}
//getter
//setter
}

How to implement database inheritance in Spring Data JPA with MapperSuperClass?

I'm trying out database inheritance of type JOINED in Spring Data JPA, referring to this article. This worked fine. But I've to implement MappedSuperClass in my project. I've implemented in the following way:
Base.java
#MappedSuperclass
public abstract class Base {
public abstract Long getId();
public abstract void setId(Long id);
public abstract String getFirstName();
public abstract void setFirstName(String firstName);
}
BaseImpl.java
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class BaseImpl extends Base {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
...
}
Super1.java
#MappedSuperclass
public abstract class Super1 extends BaseImpl {
public abstract String getSuperName();
public abstract void setSuperName(String guideName);
}
Super1Impl.java
#Entity
public class Super1Impl extends Super1 {
private String superName;
...
}
BaseBaseRepository.java
#NoRepositoryBean
public interface BaseBaseRepository<T extends Base> extends JpaRepository<T, Long> { }
BaseRepository.java
#NoRepositoryBean
public interface BaseRepository<T extends Base> extends BaseBaseRepository<Base> { }
BaseRepositoryImpl.java
#Transactional
public interface BaseRepositoryImpl extends BaseRepository<BaseImpl> { }
Super1Repository.java
#NoRepositoryBean
public interface Super1Repository<T extends Super1> extends BaseBaseRepository<Super1> { }
Super1RepositoryImpl.java
#Transactional
public interface Super1RepositoryImpl extends Super1Repository<Super1Impl> { }
I'm trying to save a Super1 object in a test case:
#Test
public void contextLoads() {
Super1 super1 = new Super1Impl();
super1.setSuperName("guide1");
super1.setFirstName("Mamatha");
super1.setEmail("jhhj");
super1.setLastName("kkjkjhjk");
super1.setPassword("jhjjh");
super1.setPhoneNumber("76876876");
System.out.println(super1Repository.save(super1));
}
But I'm getting the following error:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'baseRepositoryImpl':
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
This class [class com.example.entity.Base] does not define an IdClass
.....
Caused by: java.lang.IllegalArgumentException: This class [class com.example.entity.Base] does not define an IdClass
.......
Tried out #PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id") in Super1Impl, but still getting the same error.
The error is caused by incorrect repository interface declarations.
BaseRepository<T extends Base> extends BaseBaseRepository<Base>
should be
BaseRepository<T extends Base> extends BaseBaseRepository<T>
and
Super1Repository<T extends Super1> extends BaseBaseRepository<Super1>
should be
Super1Repository<T extends Super1> extends BaseBaseRepository<T>
As currently declared, BaseBaseRepository<Base> means a repository of Base objects and Base does not have an #Id field, hence the error.

Any way to reference an attribute of a parameter in the query?

Is there any way to reference an attribute of a parameter that is part of a query for a JPA repository?
My sample is
#Entity
public class Matchday implements Serializable {
#Id
private int matchdayNumber;
//..
//setters and getters defined
//..
//hashCode and equals methods overridden
}
public interface MyRepository extends JpaRepository<Matchday, Integer> {
#Query("... WHERE t.matchday.matchdayNumber < :matchday.matchdayNumber - 1;")
public findByCriteria(Matchday matchday);
}
The construction :matchday.matchdayNumber does not seem to be a valid syntax. Is there any other way to do it than passing the int value for matchdayNumber instead of a reference to Matchday object to this method?
Looks like this is possible with Spring JPA Data which allows SpEL in queries.
public interface MyRepository extends JpaRepository<Matchday, Integer> {
#Query("... WHERE t.matchday.matchdayNumber < :#{#matchday.matchdayNumber - 1}")
public findByCriteria(Matchday matchday);
}

Morphia: inheritance not handled properly?

I have a class that implements an interface. Why are the arraylist contents not stored in the database? Here is some code to illustrate the problem.
The class
#Entity
public class MyClass implements MyInterface {
#Id
#Indexed
public String id;
public String someField;
public MyClass(String id, String someField){
this.id = id;
this.someField = someField;
}
}
The interface
public interface MyInterface {
#Embedded
public List<String> mylist = new ArrayList<String>();
}
Test code
#Test
public void test() {
testInheritance();
}
public void testInheritance() {
MyClass myClass = new MyClass("test", "someField");
myClass.myList.add("wow");
MyClassDao dao = new MyClassDao();
dao.save(myClass);
}
public class MyClassDao extends BasicDAO<MyClass, ObjectId> {
public MyClassDao() {
super(MyClass.class, MorphiaManager.getMongoClient(), MorphiaManager.getMorphia(), MorphiaManager.getDB().getName());
}
}
Result in DB
{
"_id" : "test",
"className" : "gr.iti.mklab.simmo.util.MyClass",
"someField" : "someField"
}
Interfaces can only declare method signatures and constants (static final variables). What you want to use is an abstract base class from which you inherit.
Additional observations from your code:
The id should be ob the type ObjectId and is automatically indexed, you don't need the #Indexed
Attributes should be private or protected and you need to provide getters and setters for them
You need a default no-arg constructor in your entity class