Jackson JSON serialization of JPA Entities - jackson

I have a JPA persistence layer with many #Entity classes which have many OneToMany and ManyToMany relationships.
I want to expose that entities by RestEasy with Jackson2 as serializer to JSON as REST services.
I know about #JsonIdentityInfo for resolving circular references.
The problem is in different REST services I need to expose different subsets of Entity fields. Moreover I need to expose different levels of depts for collections (OneToMany, OneToOne etc).
For example for this simple Entities:
class User {
Long id;
String name;
Company company;
}
class Company {
Long id;
String name;
List<User> users;
List<Product> products;
}
class Product {
Long id;
String name;
List<User> users;
}
and this REST service:
class MyResource {
User getUser() { //... }
List<User> getUsers() { //... }
Company getCompany() { //... }
List<Company> getComanies() { //... }
}
In method getUser() I need to return JSON with full User object including inner Company object. But that company of course only need to include their id and name field and not full list of users. Even more important that inner Company JSON must not include products! It is logical. If we get the user we don't need products of company that related to this user. If we need them we will send another REST request.
But in method getCompany() I need to return JSON with full Company object including inner JSON arrays of User and Product objects. Of course this time that User objects doesn't need to include inner JSON for Company object.
For this reason I can't use #JsonIgnore. In one case we need some field and in another we doesn't.
Now I came up with approach of using Jackson views (#JsonView annotation). I have View class with different views for every MyResource getter.
public class Views {
public static class User {}
public static class Users {}
public static class Company {}
public static class Companies {}
// etc...
}
and MyResoruce class as
class MyResource {
#JsonView(Views.User.class)
User getUser() { //... }
#JsonView(Views.Users.class)
List<User> getUsers() { //... }
#JsonView(Views.Company.class)
Company getCompany() { //... }
#JsonView(Views.Companies.class)
List<Company> getComanies() { //... }
}
and have a MixIn classes for every Entity with every field annotated as
public abstract class UserMixIn {
#JsonView({ Views.User.class, Views.Users.class, Views.Company.class, Views.Companies.class })
public abstract Long getId();
#JsonView({ Views.User.class, Views.Users.class, Views.Company.class, Views.Companies.class })
public abstract String getName();
#JsonView({ Views.User.class, Views.Users.class })
public abstract Company getCompany();
}
public abstract class CompanyMixIn {
#JsonView({ Views.Company.class, Views.Companies.class, Views.User.class, Views.Users.class })
public abstract Long getId();
#JsonView({ Views.Company.class, Views.Companies.class, Views.User.class, Views.Users.class })
public abstract String getName();
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract List<User> getUsers();
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract List<Product> getProducts();
}
public abstract class ProductMixIn {
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract Long getId();
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract String getName();
public abstract List<User> getUsers();
}
Plurals for support cases where getUsers() doesn't need full inner Company object for every user (performance).
Of course there are just example classes. Real classes are much bigger and complex.
I do not like this approach because I am afraid that in the future it can be a nightmare (too many not manageable views). Maybe there are common approach for exposing JPA Entities as REST services? I believe it is a fairly common task. But can not find any intelligible information on how others doing this. Maybe some best practices.

Your service layer (and your REST controller layer) must expose DTOs (Data transfer objects) instead of #Entity objects.
Example :
For a Service 1 (which focus on User managment) :
public class UserDto {
private Long id;
private String name;
private CompanyDtoLight company;
}
public class CompanyDtoLight {
private Long id;
private String name;
}
For a Service 2 (which focus on Company managment) :
public class CompanyDto {
private Long id;
private String name;
List<UserDtoLight > users;
List<ProductDtoLight > products;
}
public class UserDtoLight {
private Long id;
private String name;
}
class ProductDtoLight {
private Long id;
private String name;
}
(The naming of your DTOs is yours)
How to :
You will need Mappers to transfom and reverse your #Entity to DTOs. Some lib exist like Dozer or MapStruct (there are plenty of other).

Related

Cannot create a DbSet for 'Model' because this type is not included in the model for the context

I do a Generic and using DI
so I create a empty class
public class DBRepo
{
}
and my model class to inheriting class DBRepo
public partial class UserAccount : DBRepo
{
public int Id { get; set; }
public string Account { get; set; }
public string Pwd { get; set; }
}
then this is a Interface to do CRUD
public interface IDBAction<TEntity> where TEntity : class,new()
{
void UpdateData(TEntity _entity);
void GetAllData(TEntity _entity);
}
public class DBService<TEntity> : IDBAction<TEntity> where TEntity : class,new()
{
private readonly CoreContext _db;
public DBService(CoreContext _db)
{
this._db = _db;
}
public void UpdateData(TEntity _entity)
{
this._db.Set<TEntity>().UpdateRange(_entity);
this._db.SaveChanges();
}
public void GetAllData(TEntity _entity)
{
var x = this._db.Set<TEntity>().Select(o => o).ToList();
}
}
And I Dependency Injection Service Provider in constructor
this.DBProvider = new ServiceCollection()
.AddScoped<IDBAction<DBRepo>, DBService<DBRepo>>()
.AddScoped<DBContext>()
.AddDbContext<CoreContext>(options => options.UseSqlServer(ConnectionString))
.BuildServiceProvider();
last step I Get Services
DBProvider.GetService<IDBAction<DBRepo>>().GetAllData(new UserAccount());
I will get a error message same with title
or I change to
DBProvider.GetService<IDBAction<UserAccount>>().GetAllData(new UserAccount());
I'll get other message
Object reference not set to an instance of an object.'
but the void UpdateData() is can work,
so how to fix GetAllData() problem?
The error simply is because the class you're using here UserAccount has apparently not been added to your context, CoreContext. There should be a property there like:
public DbSet<UserAccount> UserAccounts { get; set; }
Regardless of whether you end up using the generic Set<T> accessor, you still must defined a DbSet for the entity on your context.
That said, you should absolutely not be creating your own service collection inside your repo. Register your context and your repo with the main service collection in Startup.cs and then simply inject your repo where you need it. The DI framework will take care of instantiating it with your context, as long as you have a constructor that takes your context (which you seem to).
And that said, you should ditch the repo entirely. It still requires a dependency on Entity Framework and doesn't do anything but proxy to Entity Framework methods. This is just an extra thing you have to maintain and test with no added benefit.

OO polymorphism design

What is the best way to do the following:
Suppose I have a class called Person and many derived classes for specialized persons.
Suppose at the beginning of my app, I know I have to deal with a person but I won't know what kind of person it is until much later (something beyond my control so I cannot determine the Person type at the beginning).
So at the beginning I will create a Person and fill in attributes for it. Later, when I know what kind of Person it is, I would instantiate a specialized person and copy over the any saved attributes for her.
Is there a more elegant way to do this without creating two objects?
If you don't know the type of person up front, you won't be able to avoid instantiating two objects. There has to be something to contain the base Person attributes before you know the specialized person, but you can't take advantage of polymorphism without instantiating the specialized object later.
One option is to use a composition pattern, in which each specialized person contains a Person instance rather than inheriting from it. You still have to instantiate two objects, but you don't have to rewrite the code to copy over the saved attributes every time. Here's an example (C# syntax):
public interface IPerson
{
string Name { get; }
int Age { get; }
}
public class Person : IPerson
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public abstract class SpecialPersonBase : IPerson
{
private IPerson myPerson;
protected SpecialPersonBase(IPerson person)
{
myPerson = person;
}
public string Name { get { return myPerson.Name; } }
public int Age { get { return myPerson.Age; } }
public abstract string Greet();
}
public class Doctor : SpecialPersonBase
{
public Doctor(IPerson person) : base(person) { }
public override string Greet()
{
return "How are you feeling?";
}
}
public class Accountant : SpecialPersonBase
{
public Accountant(IPerson person) : base(person) { }
public override string Greet()
{
return "How are your finances?";
}
}
You could use the classes like this:
IPerson bob = new Person("Bob", "25");
// Do things with the generic object
// until you can determine the specific type
SpecialPerson specialBob;
if (bobIsDoctor)
{
specialBob = new Doctor(bob);
}
else if (bobisAccountant)
{
specialBob = new Accountant(bob);
}
specialBob.Greet();

Design pattern to save/load an object in various format

I have an object: X, that can be saved or loaded in various formats: TXT, PDF, HTML, etc..
What is the best way to manage this situation? Add a pair of method to X for each format, create a new Class for each format, or exists (as I trust) a better solution?
I'd choose the strategy pattern. For example:
interface XStartegy {
X load();
void save(X x);
}
class TxtStrategy implements XStartegy {
//...implementation...
}
class PdfStrategy implements XStartegy {
//...implementation...
}
class HtmlStrategy implements XStartegy {
//...implementation...
}
class XContext {
private XStartegy strategy;
public XContext(XStartegy strategy) {
this.strategy = strategy;
}
public X load() {
return strategy.load();
}
public void save(X x) {
strategy.save(x);
}
}
I agree with #DarthVader , though in Java you'd better write
public class XDocument implements IDocument { ...
You could also use an abstract class, if much behavior is common to the documents, and in the common methods of base class call an abstract save(), which is only implemented in the subclasses.
I would go with Factory pattern. It looks like you can use inheritance/polymorphism with generics. You can even do dependency injection if you go with the similar design as follows.
public interface IDocument
{
void Save();
}
public class Document : IDocument
{
}
public class PdfDocument: IDocument
{
public void Save(){//...}
}
public class TxtDocument: IDocument
{
public void Save(){//...}
}
public class HtmlDocument : IDocument
{
public void Save(){//...}
}
then in another class you can do this:
public void SaveDocument(T document) where T : IDocument
{
document.save();
}
It depends on your objects, but it is possible, that visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) can be used here.
There are different visitors (PDFVisitor, HHTMLVisitor etc) that knows how to serialize parts of your objects that they visit.
I would instead suggest the Strategy pattern. You're always saving and restoring, the only difference is how you do it (your strategy). So you have save() and restore() methods that defer to various FormatStrategy objects you can plug and play with at run time.

DI in Service Contract WCF

Please find below my code. Employee class implements IEmployee interface.
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> emp = new List<IEmployee>();
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(IEmployee));
TempObject.EmployeeId = "12345678";
emp.Add(TempObject);
return emp;
}
}
}
As is visible the above code does compile but wont work because interface instance cannot be created.How can I achive DI(Dependency Injection) here...If I write..
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee));
Then this class will be dependent not only on the Interface but also the class...assuming that one fine day Employee class becomes Employee2.There will be code changes at two places..
1)[ServiceKnownType(typeof(MiddleWare.Classes.Employee2))]
2)IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee2));
I want to avoid that. Can we do something at implementation of IOperationBehavior or is there a Ninject way of achieving this or am I trying to achieve impossible?
Consider a design change - Use the factory pattern to create an instance of your employee.
public EmployeeFactory : IEmployeeFactory
{
public IEmployee CreateEmployee()
{
return new Employee();
}
}
And introduce a dependency on the Factory from your middleware, so creating a new IEmployee becomes:
public class Miscellaneous : IMiscellaneous
{
private readonly IEmployeeFasctory _employeeFactory;
public class Miscellaneous(IEmployeeFactory employeeFactory)
{
_employeeFactory = employeeFactory;
}
public IEnumerable Search_Employee (string searchText)
{
List employees = new List();
IEmployee employee = _employeeFactory.CreateEmployee();
employee.EmployeeId = "12345678";
employees.Add(TempObject);
return employees;
}
And then you can inject your EmployeeFactory into Miscellaneous. And should Employee one day become deprecated and Employee2 comes along, just change the factory!
As rich.okelly points out in another answer, IEmployeeFactory should be used to create instances of the IEmployee interface, since IEmployee isn't a Service, but an Entity.
The IEmployeeFactory interface, on the other hand, is a Service, so should be injected into the service class using Constructor Injection. Here's a write-up of enabling Constructor Injection in WCF.
Had a discussion within the team.
1) Constructor based implementation is not comfortable..The service would be IIS hosted and consumed as a web-reference.Cannot ask client systems to provide FactoryImplementatedObjects in Miscellaneous class call.
2) Entity based factories is also not absolutely accurate.If I happen to have say 20 specific entities in my project like Employee,Material,Project,Location,Order then I need to have 20 Factories.Also the Miscellaneous class will have several custom constructors to support specific contract calls..
I have prepared a system which is working and DI is achieved to a great level but I feel like I am cheating OOPS..Doesnt feel correct at heart..but cannot be refuted to be wrong..Please check and let me know your comments.
I now have a IEntity Interface which is the base for all other Entities.
namespace BusinessModel.Interfaces
{
public interface IEntity
{
string EntityDescription { get; set; }
}
}
Hence forth all will implement this.
namespace BusinessModel.Interfaces
{
public interface IEmployee : IEntity
{
string EmployeeId { get; set ; }
}
}
namespace BusinessModel.Interfaces
{
public interface IProject : IEntity
{
string ProjectId { get; set; }
}
}
and so on..(Interface implementing interface..absolutely ridiculous,cheating but working)
Next,An Enum type is declared to have a list of all Entities...
namespace MiddleWare.Common
{
internal enum BusinessModel
{
IEmployee,
IProject
}
}
A DI Helper class is created which will henceforth be considered a part of Business Model and any changes to it (Implementation,Naming..) would be taken as a Business Shift.So if DIHelper class has to become DIHelper2 then this is like BIG.(Can this also be avoided??)
namespace MiddleWare.Common
{
internal sealed class DIHelper
{
internal static IEntity GetRequiredIEntityBasedObject(BusinessModel BusinessModelObject)
{
switch (BusinessModelObject)
{
case BusinessModel.IEmployee:
return new Employee();
}
return null;
}
}
}
Function is Self Explanatory...
So now finally,the contract and implementation...
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> IEmployeeList = new List<IEmployee>();
IEmployee TempObject = (IEmployee)DIHelper.GetRequiredIEntityBasedObject(MiddleWare.Common.BusinessModel.IEmployee);
TempObject.EmployeeId = "12345678";
IEmployeeList.Add(TempObject);
return IEmployeeList;
}
}
}
What do you say??
My Team is happy though :)
From your updated requirements, there is nothing related to DI in this question...
So, to create a type based on the service known types of a service contract you can use:
public class EntityLoader<TServiceContract>
{
private static readonly HashSet<Type> ServiceKnownTypes = new HashSet<Type>();
static EntityLoader()
{
var attributes = typeof(TServiceContract).GetMethods().SelectMany(m => m.GetCustomAttributes(typeof(ServiceKnownTypeAttribute), true)).Cast<ServiceKnownTypeAttribute>();
foreach (var attribute in attributes)
{
ServiceKnownTypes.Add(attribute.Type);
}
}
public TEntity CreateEntity<TEntity>()
{
var runtimeType = ServiceKnownTypes.Single(t => typeof(TEntity).IsAssignableFrom(t));
return (TEntity)Activator.CreateInstance(runtimeType);
}
}
Which is then useable like so:
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(Employee))]
IEnumerable<IEmployee> SearchEmployee(string SearchText);
}
public class Miscellaneous : IMiscellaneous
{
private readonly EntityLoader<IMiscellaneous> _entityLoader = new EntityLoader<IMiscellaneous>();
public IEnumerable<IEmployee> SearchEmployee(string SearchText)
{
List<IEmployee> employees = new List<IEmployee>();
IEmployee employee = _entityLoader.CreateEntity<IEmployee>();
employee.EmployeeId = "12345678";
employees.Add(employee);
return employees;
}
}
Obviously, the above code assumes that ALL of your service entities will contain public parameterless constructors and that there will only be one ServiceKnownType that implements each interface.

Bundling a list of entities into a component

With FluentNHibernate I have mapped a UserPreference entity which references the GeneralPreference, GeneralPreferenceOption, and Profile entities:
public class UserPreference
{
public virtual long Id { get; set; }
public virtual Profile Profile { get; set; }
public virtual GeneralPreference Preference { get; set; }
public virtual GeneralPreferenceOption Value { get; set; }
}
It's easy enough to map a list of UserPreference on my Profile entity, but what I actually would like to do is wrap this list inside another class so that I can simplify operations concerning a user's given preferences:
public class Preferences
{
public IList<UserPreferences> UserPreferences{get;set;}
public Language Language {
{
//look up the language preference here
}
}
This kind of feels like a Component, but Components were not created for this type of scenario. Does anyone have any pointers on how I might map this?
I figured out a way to do this by mapping a private property on my Profile Entity. Using the techniques from the Fluent NHibernate wiki on mapping private properties (http://wiki.fluentnhibernate.org/Fluent_mapping_private_properties) I map a collection of UserPreference on my Profile Entity. Then I create another class PropertyHandler which takes an IEnumerable as a constructor parameter and make an instance of this a public property on Profile as well:
public class Profile
{
private PreferenceHandler _preferenceHandler;
get { return _preferenceHandler ?? (_preferenceHandler = new PreferenceHandler(UserPreferences)); }
private IEnumerable<UserPreference> UserPreferences { get; set; }
public static class Expressions
{
public static readonly Expression<Func<Profile, IEnumerable<UserPreference>>> UserPreferences = x => x.UserPreferences;
}
}
Notice the nested static class. It's used to enable mapping of a private property with FluentNHibernate.
The mapping class looks something like this:
public class ProfileMappings : ClassMap<Profile>
{
public ProfileMappings()
{
//... other mappings
HasMany(Profile.Expressions.UserPreferences);
}
}
I can now use the PreferenceHandler class to create helper methods over my collection of UserPreference.
An alternative is to build extension methods for IEnumberable. This works, but I decided not to do this because
1) I'm not really extending the IEnumerable functionality and
2) my helper methods disappear inamongst all the other IEnumerable extension methods making the whole thing a bit cluttered.