OO Design of JavaBeans - java

I'm questioning the way that I have been designing my JavaBeans. For example, say I have the following:
Employee - basic employee information:
private String employee_id;
private String first_name;
private String last_name;
private String phone;
private String deptNo;
etc..
WorkflowPlayer - details about an employee in a system workflow:
private String workflow_instance_id;
private String employee_id;
private String role_class_id;
private String role_required;
private Employee employee;
private RoleClass roleClass;
RoleClass - details of a type of role (Approver, SecurityReviewer, Originator, Instructor, Manager, etc..)
private String role_class_id;
private String name;
private String label;
private String description;
These three models also correspond directly to Database tables (Employee is a read only view for me, if that matters)
Then in my view I would do something like
workflow_player.employee.first_name
workflow_player.roleClass.label
Is it acceptable to make Employee an instance variable? Or should I instead be extending WorkflowPlayer with Employee and then do
workflow_player.first_name
this makes sense for employee but not for roleClass.
workflow_player.description //NO!
I just want to use a consistent [correct] pattern

Yes, it's ok to make Employee an instance variable if you are referring to it from another table. Subclassing in this case is wrong because from your description it sounds like workflow is not a specialized kind of employee. Ask yourself if the lifecycles of these entities are the same or different, and if the subclass is substitutable for the superclass in all situations.
Subclassing should be a last resort reserved for cases where some entity is a specialized version of another entity and you want to refer to the specialized versions by their superclass.
There are specific patterns where subclassing is used in Object-relational mapping: table per class hierarchy, table per subclass, table per concrete entity, etc. The Hibernate documentation describes them. You would use inheritance in mapping objects to tables when your tables fall into one of those patterns. Even if you're not using Hibernate that's still a good example to follow.

I think role classes are a great design approach, and many developers do not use them. This matches the canonical use of role classes: when an entity participates in different activities, and within those activities, the view of that type is different. A good example would be the following. Suppose we were modeling payroll. We have a user who is both one of the employees who is getting paid, and an administrator in the app. In Java, we would have to model that as role classes because we don't have multiple inheritance, but it's really a more accurate representation because the role class, if it does confer any additional behavior or properties, it is doing so in the context of its own behavior. So for instance, whatever powers you need to grant the administrator in the payroll is confined to that realm.
It's also not an either/or situation: in the Payroll, you might want to show that some employees are also managers. That probably would best be done with inheritance, but the role class is still valid, again, as a way of representing participation.

You can't map JavaBean directly to Tables, because OO is not the same as Relational (Database).
You could use an ORM, like Hibernate, to map you JavaBean to SGBD Tables properly.
From an OO point of view, beans should be like that
public class Employee {
private String id;
private String firstName;
private String lastName;
private String phone;
private String deptNo;
}
public class WorkflowPlayer {
private String id;
private String roleRequired;
private Employee employee;
private Role roleClass;
}
public class RoleClass {
private String id;
private String name;
private String label;
private String description;
}

Related

Spring Data Neo4J reference related nodes without overwriting them on save

I'm struggling to write this, so I may have to give an example to help explain the problem I'm experiencing.
Say we have nodes of three types (these nodes may have more relationships of their own, e.g. Product Family, has product manager):
Product
Product Family
Battery
With these relationships
A product can be be in 0 or more families
A product can have 0 or more batteries.
When using spring-data-neo4j and saving a new Product, I wish to include these relatiopnships, such as the batteries they require and the product family they belong to. However if I only supply say an ID rather then a fully populated object, it overwrites this object along with properties and relations accordingly.
This isn't great as it means that I have to end up sending a fully populated object, with all it's relations everytime I wish to save something, and some of these relations may go quite deep.
My domain is as follows:
#Node
public class Product {
#Id
#GeneratedValue(generatorClass = SnowflakeGenerator.class)
private Long productId;
private String name;
#Relationship(type = "REQUIRES_BATTERY", direction = OUTGOING)
private List<Battery> batteryList;
#Relationship(type = "IN_FAMILY", direction = OUTGOING)
private List<ProductFamily> productFamilyList;
}
#Node
public class Battery {
#Id
#GeneratedValue(generatorClass = SnowflakeGenerator.class)
private Long batteryId;
private String name;
}
#Node
public class ProductFamily {
#Id
#GeneratedValue(generatorClass = SnowflakeGenerator.class)
private Long familyId;
private String name;
}
This could very well by from coming from a Relational Database mindset and is a 'limitation' of using Neo4J.
TLDR When persisting somethign in Neo4J using spring-data how can I save just a relationship, rather than a whole related Node.
You can make use of projections in Spring Data Neo4j. (https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#projections)
This gives you the option to put a "mask" on the object tree, you want to persist (and what should stay untouched).
For example in your case:
interface ProductProjection {
// without defining e.g. String getName() here, SDN would not ever touch this property.
List<BatteryProjection> getBatteryList();
List<ProductFamilyProjection> getProductFamilyList();
}
interface BatteryProjection {
String getName();
}
interface ProductFamilyProjection {
String getName();
}

MongoDB map Java POJO without org.bson.types.ObjectId

I want to map Java POJO to MongoDB and implement CRUD operations. I follow manual https://mongodb.github.io/mongo-java-driver/3.11/driver/getting-started/quick-start-pojo/ and all seems fine but one Person property is MongoDB dependent:
public final class Person {
private ObjectId id;
private String name;
private int age;
private Address address;}
This is org.bson.types.ObjectId id. This makes my domain layer dependent on MongoDB, and this actually what I would not call a POJO at all. Instead of ObjectId I would like to have String or other Java core class like Long or something like that. It could could be a kind of getter/setter too. How can I achieve this?
I tried to remove id from Person
package com.mongo_demo.domain;
public final class Person {
private String name;
private int age;
private Address address;}
and use this as my domain object, while to operate with MongoDB in DAO I will use child class:
package com.mongo_demo.mongo_domain;
public final class Person extends com.mongo_demo.domain.Person {
private ObjectId id;
}
Obviously my domain class now not have dependencies on MongoDB, but still lacks String id and no way to have getter method for it, as ObjectId id attribute is in child class.
I not sure is it fine to not have access to id value in my services code, because I could need to call delete by id operation, otherwise I will have to create my own object unique identifier, in addition to ObjectId id attribute, which will be natural key with consequent drawbacks.
PS No getter-setter methods shown, as I use Lombok #Data annotations instead.

JDBC Domain Design and Relationships

I've used Hibernate / JPA in the past, now using a combination of Spring JDBC and MyBatis.
With JPA/ Hibernate if you had a Customer, which had an address you would have a domain structure similar to code below. (minus all the annotations / config / mappings).
Does this still make sense when using JDBC or MyBatis. This is composition domain design from what I know, has-a, belongs-to, etc. However most examples I've seen of JDBC code they have domain object that bring back the IDs rather than collection, or flatten the data. Are there any performance benefits from either approach, maintainability, etc. Having worked with JPA first I'm not sure what the JDBC way of doing things are.
public class Customer {
private Long id;
private String userName;
private String password;
private String firstName;
private String lastName;
private Collection<Address> addresses
...
}
public class Address {
private Long id;
private String streetAddress1;
private String streetAddress2;
private String city;
private State state;
private String postalCode;
}
public class State {
private Long id;
private String code;
private String name;
private Country country;
}
public class Country {
private Long id;
private String code;
private String name;
}
I come across an example and here was one of their classes.
public class Question {
private long questionId;
private long categoryId;
private long userId;
private long areaId;
private String question;
private String verifyKey;
private Date created;
private User user;
private List<Answer> answers;
private long answerCount;
private String name;
// getters and setters omited...
}
Why would you fetch the userId, areaId, and categoryId instead of actually fetching the associated object? The ID is likely of no use to the front end user, I suppose you could use the ID to issue another query to fetch additional data, but seems inefficient making another round trip to the database.
You can look at this domain object as a "footprint" of database table. In your example, userId, areaId and categoryId from Question are most likely foreign keys from corresponding tables. You could never need full object data in the moment of Question creation and retrieve it later with separate db request. If you fetch all associated objects at once, you will hit at least one additional table per object (by join-s or subselect-s). Moreover, that's actually the same that Hibernate does. By default, it loads domain object lazily and hits database again if uninitialized associated object is needed.
At that time, it is better to fetch those objects that a domain object can't exist without. In your example, Question and List are coupled.
Of course, if you need user, or category, or any other associated object again in some another place of application (assume the reference to previously retrieved object has been lost), you will hit the database with same query. It should be done and could seem inefficient, because both plain JDBC and SpringJDBC have no intermediate caching unlike Hibernate. But that's not the purpose JDBC was designed for.

How to return an entity by property if it already exists?

#Entity
public class Language {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(length = 2)
private String code; //EN, DE, US
public Language(String code) {
this.code = code;
}
}
#Entity
public class ProductText {
#OneToOne(Cascade.ALL)
private Language lang;
}
ProductText text = new ProductText();
text.setLang(new Language("en")); //what if "en" exists?
dao.save(text);
Now, when I persist the ProductText, everytime a new Language object would be generated.
Can I prevent this, and in case a language table entry with code = 'en' exists this existing entity should be linked instead.
My initial goal is to not having to repeat the countryCodeString "EN" multiple times in my product-text table, but just reference the id. But does this really make sense? Should I rather just use the plain String without an extra table? (I later want to query a list of productTexts where lang = 'de').
Is the only change executing a select like dao.findByLang("en") before?
Or is there also some hibernate feature that would support this without explicit executing a query myself?
Do you process the value "en" further or do you display it directly? If only used for displaying purposes, I would just store the string, but if you want to reduce redundancy by using foreign key IDs you have to create an Entity containing the language string en which can be persisted via entity manager and which you have to obtain out of the entity manager before persisting to reuse it.
If there is only three different possible values for the language, you can also use an enum like thisĀ :
public enum Language {
EN("EN"),
DE("DE"),
US("US");
private String code; //EN, DE, US
public Language(String code) {
this.code = code;
}
// Getter...
}
#Entity
public class ProductText {
#Enumerated(EnumType.STRING)
// Or #Enumerated(EnumType.ORDINAL)
private Language lang;
}
EnumType.STRING will store the enum in the database as a String, while EnumType.ORDINAL will store it as an int. Int is maybe a little more efficient, but the mapping could change if you insert a new value in your enum. String is more flexible since it will use the names of your enum members.
In both case, you don't have to manage a separate entity and hibernate will not create an additional table, and it's more type-safe than using a plain string.
If the only value in Language is a 2 or 3 letter string, why not just have the string as a member? This will be quicker and more efficient.

Unable to use #Serialize with requestfactory

I've created an entity with a pojo (ProductVariations) using the label #Serialize to be persisted in GAE through objectify:
#Entity
public class Product extends DatastoreObject{
//Reference without the colors and size information
#Index private String ref;
private double price;
private String details;
private String description;
#Serialize private ProductVariations pVariations;
private List<String> tags = new ArrayList<String>();
//Getters & Setters
}
The problem is that I don't see how to access my pojo with requestfactory because ProductVariations is not a domain type.
In any other case I would use an embeded object but in this particular case I have a nested collection inside ProductVariations witch is a collection in itself (ProductVariations extends ArrayList).
Any suggestions in how to achieve this?
Thank you.
Not sure I understand your question, but you need to implement Serializable in Product if you want to send it over RPC.
Beyond that, are you having problems storing ProductVariations? It's an interesting concept. If it isn't working:
Can you keep ProductVariations in its own #Entity?
Then keep a Key in Product class (or a Long that can you can create a Key from).
For convenience you can also leave ProductVariations in Product but mark it with #Transient and then populate it from the Key/Long in the factory that does your ofy.get().

Categories