How hibernate change classes or object at run time - java

I was trying to understand how hibernate work in the sense that how putting #Entity on a class makes it a persistent class ?
i.e
#Entity
class A{
private int b;
public int getB(){
return b;
}
public void setB(int b){
this.b = b;
}
}
behaves like below written class at runtime
class A{
private int b;
public int getB(){
return (SQL code to fetch b from DB)
}
public void setB(int b){
(SQL code to set b in DB)(b);
}
}
If we say it is using reflection then how it is changing the code that is inside the methods ?

Hibernate proxied / runtime-weave your class. Meaning when other classes invoke methods of your class, it doesn't invoke it directly, but it invokes the proxy. This proxy then contains logic that involves persistence context operations.
Have a look at library such as cglib or aspectj if you want to delve deeper in this topic (not necessarily the ones used by hibernate)

Related

cast or create obj1 from obj2 where obj1 and obj2 extends same abstract class

For example I have:
public abstract class SomeAbstract {
private int a;
private int b;
..
private int z;
}
public class A extends SomeAbstract {
private String aField;
}
public class B extends SomeAbstract {
private long bField;
}
(default constructors/setters/getters are omitted)
I have some instance of a class A and i wanna create
instance of a class B from A(abstract fields).
Yes, I can use abstract class constructor or create constructor for class B like this :
public B(A a) {
this.a = a.getA();
this.b = a.getB();
..
this.z = a.getZ();
}
But since I have many fields this does not look nice and convenient
Is there another way?
You can create a constructor in the super class that receives another super class.
public abstract class SomeAbstract {
/* attributes... */
public SomeAbstract() {
}
protected SomeAbstract(SomeAbstract another) {
this.a = another.a;
/* and on... */
}
}
And reuse this constructor in sub classes:
public class B extends SomeAbstract {
public B(A a) {
super(a);
this.specificAttribute = a.somethingElse;
}
}
If you have that many fields and don't want/need to create the whole code manually, you can use an external library that helps you with the mapping between classes. Some options are:
Dozer that maps data between objects. The configuration can be done through XML or annotations. This library works (AFAIK) using reflection, so it may have a direct impact on the performance of your application.
Orika that generates byte code at runtime to map data between objects. The configuration is done at design time. This library works (AFAIK) using reflection, so it may have a direct impact on the performance of your application, when I tested it, the execution time was faster than Dozer (about 7x faster).
MapStruct that will generate code to map the classes (using getters and setters, validating nulls and on) and this code will be available for at runtime. The configuration is done at design time through annotations. This library works (AFAIK) using Java code, so it's similar to the normal execution of the code (e.g. execute b.setValue(a.getValue())).

How to test methods which using private parameters without getters/setters(Injected)?

In Java like this:
#Injected
private Int a;
#Injected
private Int b;
public void myMethod() {
System.out.println(a);
System.out.println(b);
}
I have no idea how to test this method.
I do not recommend you to write code like this and if it is already written to refactor it. The idea of dependency injection is to have dependencies which can be injected runtime. At the moment they are injected by reflection so as davidxx says you have to use reflection to set values which you need . This may cause you a lot of headaches.
Instead of using field injection like this :
#Inject
private Int b;
You can use setter injection like this :
#Inject
public void setB(int b) {
this.b = b
}
Another way is to use constructor injection like this:
public YourClass {
private int a;
private int b;
#Inject
public YourClass(int a, int b){
this.a = a;
this.b = b;
}
}
Assuming what you meant is to use #Inject (from javax.inject), then you could use #InjectMocks from Mockito, though this probably won't work too well with primitive values (assuming you meant to write int rather than Int).
There are some caveats to using this, however: https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/
How to test methods which using private parameters without
getters(Injected)?
Only with reflection as you don't have direct way to set these fields.
You can do this at hand or with tool such PowerMock.
The WhiteBox class allows to achieve it.
Now, I don't advise this way.
It is tricky and dependencies of the component should be visible to make them clear and to also allow them to be naturally switchable and testable.
You are not forced to use setters.
You could use a constructor injection.
#Inject
public Foo(Int a, Int b) {
this.a = a;
this.b = b;
}
It is a little more verbose but it is really not a big deal.

Handle circular dependency in CDI

I have situation like this. I cannot see any errors but I am not getting my results.
#ApplicationScoped
public class A {
private B b;
#Inject
public A(B b) {
this.b = b;
}
}
#Singleton
public class B {
private A a;
#Inject
public B(A a) {
this.a = a;
}
}
Is this type of dependency injection is wrong?
Can any one help me with this.
I'd avoid this circular dependency, there is a few reasons to do that.
Comment on this article
A messy constructor is a sign. It warns me that my class is becoming a monolith which is a jack of all trades and a master of none. In other words, a messy constructor is actually a good thing. If I feel that the constructor of a class is too messy, I know that it is time to do something about it.
And this one
You’ll find cases where a class A needs an instance of B and B needs an instance of A. This is a typical case of a circular dependency and is obviously bad. In my experience the solution is either to make B a part of A when the two are so strongly dependent that they really should be one class. More often though there is at least one more class C hiding in there so that B doesn’t need A but only C.
As Oliver Gerke commented:
Especially constructor injection actually prevents you from introducing cyclic dependencies. If you do introduce them you essentially make the two parties one because you cannot really change the one without risking to break the other, which in every case is a design smell.
Here is a small example of what I might do.
public class A {
private B b;
#Autowired
public A(B b) {
this.b = b;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithB() {
b.doSomeWork();
}
}
public class B {
private A a;
#Autowired
public B(A a) {
this.a = a;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithA() {
a.doSomeWork();
}
}
After refactoring it might look like this.
public class A {
private C c;
#Autowired
public A(C c) {
this.c = c;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithC() {
c.doSomeWorkThatWasOnA();
}
}
public class B {
private C c;
#Autowired
public B(C c) {
this.c = c;
}
public void doSomeWork() {
// WORK
}
public void doSomeWorkWithC() {
c.doSomeWorkThatWasOnB();
}
}
public class C {
public void doSomeWorkThatWasOnB() {
// WORK
}
public void doSomeWorkThatWasOnA() {
// WORK
}
}
Quoting from Section 5 of the CDI Specification 1.2:
The container is required to support circularities in the bean
dependency graph where at least one bean participating in every
circular chain of dependencies has a normal scope, as defined in
Normal scopes and pseudo-scopes. The container is not required to
support circular chains of dependencies where every bean participating
in the chain has a pseudo-scope.
ApplicationScoped is a normal scope, so this cycle should work.
In your sample, class A cannot be proxied since it's missing a zero-argument constructor. Adding this constructor (which may have protected or package visibility), your sample deploys without problems.
You can also use Setter based Dependency Injection to resolve this issue.
There is definitely a solution to this. Let me quote myself:
The right solution is to inject javax.enterprise.inject.Instance, where T is type of the class to be injected. Since the type is directly Foo, calling get() method on an object typed as Instance is guaranteed to inject the right object all the time. This approach works very well, because the instance is obtained dynamically from the container by the implementation itself and only as needed. Therefore, the responsibility of dependency retrieval is left to your code - your code is responsible not to make an endless loop.
#Named
public class Foo implements Fooable{
#Inject
private Instance<Foo> foo;
public void executeFirst(){
foo.get().executeSecond();
}
#Transactional
public void executeSecond(){
//do something
}
}

Encapsulation over engineering

In the doJob() method, B is referenced through getter. I personally do not favor this idea and would prefer just b.execute() since I know for sure that getB() will never be modified.
I know that by doing this, would be moving away from encapsulation, but isn't encapsulating B object an overkill here?
class A{
private B b;
public void setB(B b){
this.b = b;
}
public B getB(){
return b;
}
public void doJob(){
getB().execute();
}
}
It really doesn't matter if you access B through its attribute or getter as long as the attribute remains private (so yes, calling getB() is an overkill, it certainly doesn't break any design pattern).
In this scenario it's probably overkill because it's a simple object. But what if there was lazy loading and your object looked like this..
class A{
private B b;
public void setB(B b){
this.b = b;
}
public B getB(){
this.b = this.b ?? new B();
return this.b;
}
public void doJob(){
getB().execute();
}
}
Then it's not overkill to access your private members via a property.
I don't know if this will help you, but if B is a dependency then your object should be setup like this where IB is the interface of the concrete object B. It's an inversion of control pattern to decouple the concrete object B from A. But this is overkill for simple object graphs as well
class A{
private IB b;
// Use inversion of control
public A(IB b){
this.b = b;
}
public IB getB(){
return this.b;
}
public void doJob(){
getB().execute();
}
}
You are minimizing risk by using the getter. What if it turns out the B was null in one use case or you need to initialize B because of a new requirement. This pattern allows you to update getB() without having to change anything else in A.
public B getB(){
if(b == null) {
b = getEntityManger().findB(); // or wherever you wanted to get B from
}
return b;
}
Providing accessor/mutator methods for a private member enables you to add error checking, change the storage of the member, and do other things internal to the class. How you access the member within the class is your choice.
If you discover you need to change the class internals later, then switching to the accessor/mutator can be done then. Certainly this simple example does not require the accessor (getter) method. But realize that a more complex case might benefit by using the getter.
That is ok only if you make the whole class, or at least make the setter and getter, final.
Otherwise this breaks:
class A2 extends A {
private B2 b;
#override
public void setB(B b){
this.b = new B2(b);
}
#override
public B getB(){
return b.toB();
}
}
Now calling the non-overriden doJob() will use wrong member variable.

Java design, how do I avoid passing object down the hierarchy?!? Impossible?

I have a number of classes, please allow me to introduce them and then ask my question at the end:
I have a container class which contains two objects in a composite relationship:
public class Container{
A a;
B b;
public someMethod(){
a.getC().myMethod(b);
}
}
A and B are superclasses (or Interfaces), with subtypes that can also be the type held in the composite relationship.
A contains a member of (interface) type C:
public class A{
C c;
}
public interface C{
public void myMethod(B b);
}
public class D implements C{
public void myMethod(B b){
//This code will modify the state of object b, in class Container.
b.changeState();
}
}
public class E implements C{
public void myMethod(B b){
//This code will modify the state of object b, in class Container.
b.changeState();
}
}
My problem is that I wish to modify the state of object b from a method starting in the container class, which eventually calls code down the hierarchy, to classes D and E- calling myMethod() via dynamic binding. I want to do this because I am going to use polymorphism to run the correct myMethod() (depending on whether the type of object is D or E) and I wish to do this, rather than write IF statements.
So my problem is that it seems very bad continually passing the instance of object b down the class hierarchy to myMethod, so that I can run b-specific code to modify the state of b. Is there anything else I can do to modify b from d and e (collectively known as c)?
I can get this to work using just interfaces but without using generics- but when I added generics i had problems with types and that made me start to think if my whole design was flawed?
EDIT: I could probably do this easily just by using IF statements- but I wanted an elegant solution using polymorphism of classes D and E.
First of all, if I understood your question correctly, no instance of B is being "passed down" in your code. Dynamic dispatch will simply cause the myMethod() implementation in the actual type of a to be called with an instance of B as argument.
While it may be tedious to have to write the argument explicitly every time you implement myMethod(), there's nothing wrong with it.
The alternative is to give each subclass/implementation of A an attribute of type B. In this case, however, you would have to pass your B instance down the chain of constructors to the class that actually has your B attribute.
Your code would become:
public class A{
C c;
public A(C c) {
this.c = c;
}
public interface C{
public void myMethod(B b);
}
public abstract class CC {
protected B b;
public CC(B b) {
this.b = b;
public class D extends CC implements C {
public D(B b) {
super(b);
}
public void myMethod(){
b.changeState();
}
}
public class E extends CC implements C {
public E(B b) {
super(b);
}
public void myMethod(){
b.changeState();
}
}
And then somewhere, e.g. in Container's constructor:
b = new B();
a = new A(new E(b));
You could pass the instance of B to the constructor of E. (or use a setter). That poses issues in itself, but at least it avoids having to pass B down every time you call myMethod(), which now needs no arguments.
e.g.
somewhere inside B
E myE = new E(this);
and, inside E
final B myB;
public E(B myHigherLevelThing) {
this.myB = myHigherLevelThing;
}
public void myMethod() {
myB.changeState();
}
Use the most general interface for the declarations, I'm a little confused about your full hierarchy so there may be room for improvement there...

Categories

Resources