I have two classes(Pojos) name Soldbookdetails.java and Bookdetails.java,
what I want to do is, I have to get data from Bookdetails table(Soldbookdetails.java) and save the same data to my Soldbookdetails table(Soldbookdetails.java).
ActionClass.java
private Double[] id;//With getter and setter
private Double[] quantity; //With getter and setter
Bookdetails book=new Bookdetails();//pojos,//With getter and setter
Soldbookdetails sbook=new Soldbookdetails();//pojos,//With getter and setter
BookdetailsDAO dao=new BookdetailsDAO();
SoldBooksTransactionDAO dao2=new SoldBooksTransactionDAO();
------------
(Note: my both pojo are same only their Class name are different)
My problem: I am unable to save record from Bookdetails.java to Soldbookdetails.java .(See My above ActionClass.java class,inside the execute method , i have mention the ERRROR).
After getting record by Bookid , i am unable to save the record into my Soldbookdetails.java.
Please help me to solve my problem.
Your saveSoldbooks(Soldbookdetails s) method takes an object of Soldbookdetails as argument but you are passing an object of class Bookdetails.
The thing you can do is you can add a method that copies the attributes of an Bookdetails object to an Soldbookdetails object (without the id field). Then you should try to save the object of Soldbookdetails using your existing method.
While keeping sold books and books in separated tables is (IMO) good perfomance issue, I think you don't need to create separated IDENTICAL classes for them.
Consider making you're class BookDetails an abstract and annotating it as MappedSuperclass:
#MappedSuperclass
public abstract class BookDetails{
// fields
// getters
// setters
}
#Entity
#Table(name="SoldBooks")
public class SoldBookDetails extends BookDetails{
// Currently blank
}
#Entity
#Table(name="BookDetails")
public class TradingBookDetails extends BookDetails{
// Currently blank
}
While currently you're classes are identical, at future you may decide to create others book types (like other table and classes for purchasing books to store or books in the way to customer) and, of course, there may appear different logic for SoldBooks and others, and in this case such 'abstraction' will simplify maintenance.
The only changes to you're saveSoldBook I currently see is to change it's argument type or provide type check in the body of the method, as long as while argument type is BookDetails, you can pass in the function any variable, derived from it - therefore, TraidingBookDetails, SoldBookDetails etc. (Changes needed depends on you're logic in this method and DAO itself).
Related
Is it possible to have a column definition inside a super class Entity for use by sub class Entities?
I have adopted the table-per-subclass hierarchy to represent different types of 'businesses' which inherit from a 'super business'. So each business type has its own table in the database and there is also a generic 'business' table which contains information which is common to all business types.
Each of these businesses has a foreign key column called 'parent_id' which points to another business of the same type (so businesses can belong to other businesses of the same type). This means each of my business type classes has its own 'parent' attribute with corresponding getters and setters.
I want to use generics to declare a 'parent' attribute (along with getters and setters) in the 'super business' so that it can be written once for all businesses instead of once for every type of business.
I achieved something close to this by putting this stuff into a new #MappedSuperClass (CommonBusiness) between my 'super business' class and my 'business type' classes, which looks like this:
SuperBusiness > CommonBusiness > (BusinessType1, BusinessType2, BusinessType3)
But I want to know if it's possible do this without the 'CommonBusiness' class in between.
My original question could be rephrased as: Is it possible to define columns in a superclass Entity so that the child Entity treats some columns as if they are from a MappedSuperClass?"
(I've looked everywhere and haven't found anything! Also I can't post code, because it doesn't belong to me, sorry!)
I would do something like this:
public class SuperBusiness<T extends SuperBusiness> {
protected T parent;
...
}
public class CommonBusiness<T extends SuperBusiness> extends SuperBusiness<T> {
...
}
public class BusinessType1 extends CommonBusiness<BusinessType1> {
...
}
public class BusinessType2 extends CommonBusiness<BusinessType2> {
...
}
public class BusinessType3 extends CommonBusiness<BusinessType3> {
...
}
I am using Jest to query Elasticsearch and so far it has been great. Jest's documentation says:
Result can be cast to List of domain object;
... and shows this example:
SearchResult result = client.execute(search);
List<SearchResult.Hit<Article, Void>> hits = searchResult.getHits(Article.class);
// or
List<Article> articles = result.getSourceAsObjectList(Article.class);
getSourceAsObjectList is deprecated, and I am using:
List<SearchResult.Hit<ImmutableConceptDocument, Void>> concepts = result.getHits(ImmutableConceptDocument.class);
... Where ImmutableConceptDocument is an immutables generated class - otherwise pretty straight forward POJO, with attributes named as I see under the source of my search results.
However, when I use the above line, I don't get the source properties mapped, I do get other details like score, type, index etc. mapped.
What am I missing? Does the domain class need to have specific Jest annotations or something like that?
I can't see any good examples in the unit tests too. This one maps to Object.class and that does not show me a mapping example.
Here is the immutable class:
#Value.Immutable
public abstract class EsConceptDocument {
public abstract String term();
public abstract Category type();
public abstract List<String> synonyms();
}
... where Category is an enum type.
As Val pointed out in the comments, this was because immutables.io makes the generated class' constructor private (and exposes a builder).
I removed immutable from this class and wrote a constructor and getters and it worked.
All I could gather from Google is that:
Hibernate uses a proxy object to implement lazy loading.
When we request to load the Object from the database, and the fetched Object has a reference to another concrete object, Hibernate returns a proxy instead of the concrete associated object.
Hibernate creates a proxy object using bytecode instrumentation (provided by javassist). Hibernate creates a subclass of our entity class at runtime using the code generation library and replaces the actual object with the newly created proxy.
So, what exactly does the Proxy object contain?
Does it contain a skeleton object reference object with only the id field set? Others field will be set when we call the get method?
Does the Proxy object contain the JDBC statement to fetch all data required to fully populate the referenced object.
Is there something else I might be missing?
I am not asking for spoon feeding but if you can provide any link with information that would be great.
Any correction to above description will also be welcomed.
Example.
class Address {
String city;
String country;
}
class Person{
int id;
String name;
Address address;
}
When we try to load the Person object, Hibernate will subclass Person class like:
class ProxyPerson extends Person {
int id;
String name;
Address proxyCGLIBObject;
}
and return a ProxyPerson object. Object of ProxyPerson will have a value for id and name but proxy for Address.
Am I correct?
What can I expect from adding a toString() method on the proxy object?
The Hibernate Proxy is used to substitute an actual entity POJO (Plain Old Java Object).
The Proxy class is generated at runtime and it extends the original entity class.
Hibernate uses Proxy objects for entities is for to allow [lazy loading][1].
When accessing basic properties on the Proxy, it simply delegates the call to the original entity.
Every List, Set, Map type in the entity class is substituted by a PersistentList, PersistentSet, PersistentMap. These classes are responsible for intercepting a call to an uninitialized collection.
The Proxy doesn't issue any SQL statement. It simply triggers an InitializeCollectionEvent, which is handled by the associated listener, that knows which initialization query to issue (depends on the configured fetch plan).
I have a form that should be bind to a complex object that wrap a lot of children, every time before loading this form I have to initialize all children object in a method that only have a lot of new statements and calling a setter method, I have to repeat this scenario for a lot of forms and other complex objects
Is there a better strategy than the initializeEmployee method?
For example:
#Entity
public class Employee {
Integer Id;
Contract contract;
Name name;
List<Certificate> list;
// getter and setters
}
#Entity
public class Contract {
String telephoneNum;
String email;
Address address;
// getter and setters
}
#Entity
public class Address {
String streetName;
String streetNum;
String city;
}
public class Name {
String fName;
String mName;
String lName;
// getter and setters
}
// And another class for certificates
public initializeEmployee() {
Employee emplyee = new Employee();
Name name = new Name();
employee.setName(name);
Contract contract = new Contract();
Address address = new Address();
contract.setAddress(address);
employee.setContract(contract);
// set all other employee inner objects,
}
EDIT:
According to below answers, it seems that there is no optimal answer. However, I could use the Entity constructor or a Factory Design Pattern.
But both solutions don't solve my other problem in initializing all fields strategy with Required and Optional fields.
For example:
If I have Name as required (i.e. the Employee entity will not persisted if Name object attributes are empty, on the other side the Contract entity is an optional. and I cannot persist an empty Contract object to the database, so I have to make it null first before persistence, then reinitialize it after persistence like the following
// Set Contract to null if its attributes are empty
Contract contract = employee.getContract()
if(contract.getTelephoneNum().isEmpty && contract.getEmail().isEmpty() && contract.getAddress().isEmpty()){
empolyee.setContract(null);
}
employeeDAO.persist(employee);
// reinitialize the object so it could binded if the the user edit the fields.
employee.setContract(new Contract());
You can add constructors (it is their role after all) to your entities to instanciate these fields if having a null value has no meaning for your case.
Another way, if you don't like adding contructors, is to add a static factory method to instanciate your bean which will look like initializeEmployee() but with potential parameters and returning an Employee object. http://en.wikipedia.org/wiki/Factory_method_pattern
Similarly, you can instanciate your collections too, as there is probably no meaning for a null collection (but there is one for an empty collection).
You can add behaviour to your entities, don't be locked in Anemic Domain Model which is considered an anti-pattern by Martin Fowler http://www.martinfowler.com/bliki/AnemicDomainModel.html
EDIT
I see you are using dao.persist(entity): you are probably using JPA. If so, maybe it is best to not modify your object graph (on the front side) and add an EntityListener (in the persistence layer) for Employee: here is a link for Hibernate EntityListener (it is a JPA feature, so if you are using another framework don't worry) http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html
With an EntityListener, you can add small "aop like" actions before persistence and after. This will allow you to not deal with null values on the domain and front layers and will ensure that every entity fits in any case (better validation).
In PrePersist: you'all add your code to check null values (possibly with custom methods "isEmpty()" on the domain classes) and nullify fields if needed. In PostPersist you add your new object.
I couldn't get what you really need, but I think you could try this way:
#Entity
public class Employee {
Integer Id;
Contract contract = new Contract();
Name name = new Name();
List<Certificate> list;
// getter and setters
}
#Entity
public class Contract {
String telephoneNum;
String email;
Address address = new Address();
// getter and setters
}
I'm not sure it reduces the verbosity at all but since this is a UI issue, you could initialize the editable objects in your flow.xml and then put it all together in an Employee instance prior to saving to the DB.
<on-start>
<evaluate expression="new foo.bar.Name()" result="flowScope.employeeName" />
<evaluate expression="new foo.bar.Contract()" result="flowScope.contract" />
<evaluate expression="new foo.bar.Address()" result="flowScope.address" />
</on-start>
Actually I would advise against using Hibernate Entities directly in GUI. In many cases (I assume in yours too, but I'm missing some details on your use-case) it is useful to use a Data Transfer Object pattern instead. You can create such DTO that is GUI specific, has only those fields that you need, and the structure is only as complex as needed.
After specific user action (like save e.g.) use those DTOs (on event handling) to create your Entities that will be persisted.
Unless your case is that just entering the GUI screen causes Entities creation, then I would recommend Factory pattern.
Also note that in many cases initialization of component objects that are making up the main object (Employee in your example) are better to be initialized in constructor of main object, eg. if you expect that Contract cannot be null - initialize it in constructor. The same for the list of Certificates and others.
I have a college management portal. I have to create the following classes for depicting the model.
class Address
{
String street;
String city;
}
class Contact
{
String phone;
String mobile;
}
abstract class Person
{
String name;
String age;
Address address;
Contact contact;
}
class Student extends Person
{
String course;
String stream;
String rollno;
}
class Faculty extends Person
{
String department;
String faculty id;
}
Now should i use the getter-setter methods for instance initialisation or constructors ?
What about the aggregation in class Person ??
How should the constructor work there ??
Yes I think you should have getter & setter methods for the model objects. Your attributes of the class should be made private.
The constructors are used to allow the mandatory information to be passed for object construction without which the object cannot be build (or the object is useless). Its like you cant create a person without name & age. In your case the address & contact many be optional. So you can set the address/contact information using mutator methods.
As Srinivas mentioned the constructors are not the alternatives for mutator method.
The purpose of constructor is make mandatory things available for object construction. Its like without raw material you cant build a building.
For this stuff these you need "beans" = private member variables with getters and setters for each. Depending on your needs you could create a constructor that has certain parameters to be set in the object at instantiation but also through the setters not directly (as certain setters might operate on the set value in a certain way so it is best that you do not mess up directly with stuff like this.student = "name").
For the faculty case I do not see why it extends Person and I do not think it should. As you say these are models they should reflect structures of tables in a database so at most each of them would extend an abstract class or implement a certain interface but not each other.
For the person aggregation also I believe that Contact And Address should be Integers as they represent a Foreign Key in another table and think about the case of many-to-many relation.
Models are first of all a reflection of the database in the application.