Hibernate annotations -- before field declaration or before getter-setter - java

In Hibernate, placing there #Id annotation
before the field declaration itself
#Id
private int id;
and before its getter and setter
#Id
public int getId() { return this.id; }
public int setId(..) { .. }
are two different things. This difference takes effect if there's some processing in getter/setter.
The Q is, is there such an issue for non-key fields-- those without the #Id annotation?
My key fields aren't any processed. However, among the others, I've got some fields that i am validating/changing the values before setting. For those fields, should i put the annotations before their getters-setters?
I didn't hit a brick wall as far as I could observe. however - would like to make sure.
TIA.
Note: saw the useful discussion: Where to put hibernate annotations?.

Well no issue for non-key fields, but personally I prefer fields annotation, expecially if you don't have to do some business logic on entity level: code is cleaner, all db related stuff is at the beginning of the class, you don't have strange issue with equals methods (which always use fields - it happened to me) plus, if you have other methods not strictly related to db handling you have to set them #Transient.

Related

Do I need to follow the bean naming conventions when using JPA annotations?

If I'm using JPA's annotations to specify my mapped fields, like so:
public class PersistedEmployee {
private Integer id;
#Id//Plus some #GeneratedValue cruft in the real example
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
}
Does that ID need to follow the getFoo bean naming convention? Or are the annotations sufficient for identifying how to map this POJO?
The underlying provider is Hibernate, in this case, but I'm also curious if that makes a difference or not.
JPA supports two ways to access properties. Either through getters and setters or through reflection directly accessing the field.
If you use the first, the getters and setters need to follow the proper naming convention, if you use the second, they don't have to exist, and you can use whatever accessors/mutator you like.
What access type is used is defined by the place where you put the #id annotation. If it is on a field, field access is used. If it is on a getter/setter property access is used.
JPA spec.
The persistent state of an entity is accessed by the persistence provider
runtime either via JavaBeans style property accessors (“property
access”) or via instance variables (“field access”).
It's publically available, so if using JPA you really ought to get it, or a book/documentation that presents it.

Discouraged method, not deprecated

Some java classes need to have private properties with a public getter and setter in order to function properly. For example JSF beans and JPA entities need them. If it wasn't for those libraries, there are probably some properties which should not have any getters and definitely not setters. Also empty constructors are oftenly discouraged for use by custom code. For example
#Entity
public class MyEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public MyEntity() {}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
In this class the method setId should never be called by manual code. The method is not deprecated though, so an #Deprecated annotation would be wrong.
Is there another way than #Deprecated to tell a method should not be used?
JPA entities don't need public getters and setters. Values are set using reflection (at least when using EclipseLink or Hibernate which you're probably using).
In this particular example you could simply leave the setter out, I have made a habit out of it and never had a problem with it. Note: Stick to Java naming conventions when it comes to properties and getters/setters. Some libraries/frameworks (wrongly imo) depend on this.
As for the global concept of the question, I am surprised I didn't see a suggestion that includes documentation. Documentation has, is, and will probably always be your greatest communication to users of your code.
/**
* WARNING! DO NOT USE THIS UNLESS YOU ARE GOD!
* This will probably break stuff unless...
* ....
*/
public void doEvilHackishThings()
{
// Stuff happens here.
}
If you document your code properly, developers know when they're likely to break stuff. Make sure you don't apply voodoo code etc. Good documentation describes in some detail what it does and how it does it. No developer in his right mind will touch the example method without understanding why it is evil.
You could hide getters and setters by using an interface that is backed by that concrete class. This would also encourage Tell, don't ask, because there aren't any getters you could use on the interface. The constructor usage can also be hidden in factories.

Is it possible to have immutable fields in Hibernate/JPA?

In our application, we need to have fields that are assignable only once.
At first we thought of encapsulating the fields and making the setters private. However, some questions arouse:
Without a public setter, is Hibernate still able to map the field from the database?
Can I strip out the setter and make the field mutable only in the entity constructor?
Finally, is there any standard JPA way to make a field immutable?
Thanks in advance.
Try
#Column(updatable = false)
And make your setter private. (Leave your getter public if you want)
I think this is the best practice.
P.S.: JPA uses field access if you annotate your fields and uses getter/setter access if you annotate your getter method.
Ad. 1: I believe JPA uses plain private fields for both read and write if annotations are placed on fields and not on getters. Recently I discovered that Hibernate as an underlying JPA provider does not even need get*() and set*() methods at all. This was truly enlightening solution since from the beginning I thought Hibernate needs accessors. So the answer is: you don't need setters as far as Hibernate is concerned.
Ad. 2: However please note that Hibernate still needs no-arg constructor, otherwise it will fail to load entities with a descriptive exception. This is also a JPA requirement.
Ad. 3: No, there isn't. Remember that your collections would also had to be immutable.
Try
#Column(updatable = false)
From javadoc:
Whether the column is included in SQL UPDATE statements generated by
the persistence provider.
In JPA 2.0 you have two ways to define what attributes should be persisted:
Access(FIELD) - the fields name are persisted,
Access(PROPERTY) - the properties name are persisted.
If no Access(-) annotation is used, the decision what access will be used depends on where you put your #Id annotation. If you put it next to your field - Access(FIELD) will be used. If you put it next to your accessor - Access(PROPERTY) will be used.
Therefore, if you use Access(FIELD) you don't have to have an appropriate JavaBeans-style accessor for particular field. You can have a private field named 'myField' and a public setter for it named 'public setBlahBlah(-)'. The JPA will persist just the 'myField'.
You can mark an entity with #Entity(mutable=false) or #Immutable annotations for the framework to make use of this fact for performance gain in caching and such. (Hibernate)
Then you can use an immutable wrapper class like this:
public class ImmutableStuff {
private final FooField barValue;
public ImmutableStuff(Stuff stuff) {
barValue = stuff.barValue;
}
public FooField getBarValue(){
return barValue;
}
}

I have a feeling that adding fields marked with #Transient annotation to entity is very bug-prone. Am I right?

I have some philosophical intuitive feeling that adding fields which doesn't mapped to the DB corrupts entity classes and is a wrong way of solving problems.
But are there any concrete situations where using #Transient fields leads to implicit and hard fixing problems?
For example, is it possible that adding or removing 2nd level cache will break our app when there are #Transient fields in our entities?
Considerable update: after some thinking on #Transient fields it seems to me that #Transient fields just should be used in a proper way.
By 'proper way' I mean that entity always should have same behavior. It means that it's a very error-prone behavior when getters returns null's from time to time depending on #Transient field value. And it means that #Transient fields should always be initialized.
And I see only 2 cases of proper usage:
#Transient fields should be initialized in object's constructor:
#Entity
public class SomeEntity
#Id
private long id;
#Transient
private String transientField;
public SomeEntity () {
transientField = "some string";
}
...
}
#Transient fields can be lazy initialized:
#Entity
public class SomeEntity
#Id
private long id;
#Transient
private String transientField;
public String getTransientField () {
synchronized (lock) {
if (transientField == null) {
transientField = "some string";
}
}
return transientField;
}
...
}
Can anyone coment these 2 cases or describe other cases which I missed?
I am using the Transient annotation in some projects that persist with hibernate as well and didn't have any problems yet.
It is usually used for fields that can be determined by other persistent properties and using a cache should work also, because Javas Serialization mechanisms (caches usually expect the cached objects to be serializable) take the Transient annotation into consideration, too. I think it is preferrable to use transient getter and setter properties that provide the information instead of instance fields whenever possible.

Why does JPA have a #Transient annotation?

Java has the transientkeyword. Why does JPA have #Transient instead of simply using the already existing java keyword?
Java's transient keyword is used to denote that a field is not to be serialized, whereas JPA's #Transient annotation is used to indicate that a field is not to be persisted in the database, i.e. their semantics are different.
Because they have different meanings. The #Transient annotation tells the JPA provider to not persist any (non-transient) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a #Transient property and still serialize it.
As others have said, #Transient is used to mark fields which shouldn't be persisted. Consider this short example:
public enum Gender { MALE, FEMALE, UNKNOWN }
#Entity
public Person {
private Gender g;
private long id;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }
#Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}
#Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}
When this class is fed to the JPA, it persists the gender and id but doesn't try to persist the helper boolean methods - without #Transient the underlying system would complain that the Entity class Person is missing setMale() and setFemale() methods and thus wouldn't persist Person at all.
Purpose is different:
The transient keyword and #Transient annotation have two different purposes: one deals with serialization and one deals with persistence. As programmers, we often marry these two concepts into one, but this is not accurate in general. Persistence refers to the characteristic of state that outlives the process that created it. Serialization in Java refers to the process of encoding/decoding an object's state as a byte stream.
The transient keyword is a stronger condition than #Transient:
If a field uses the transient keyword, that field will not be serialized when the object is converted to a byte stream. Furthermore, since JPA treats fields marked with the transient keyword as having the #Transient annotation, the field will not be persisted by JPA either.
On the other hand, fields annotated #Transient alone will be converted to a byte stream when the object is serialized, but it will not be persisted by JPA. Therefore, the transient keyword is a stronger condition than the #Transient annotation.
Example
This begs the question: Why would anyone want to serialize a field that is not persisted to the application's database?
The reality is that serialization is used for more than just persistence. In an Enterprise Java application there needs to be a mechanism to exchange objects between distributed components; serialization provides a common communication protocol to handle this. Thus, a field may hold critical information for the purpose of inter-component communication; but that same field may have no value from a persistence perspective.
For example, suppose an optimization algorithm is run on a server, and suppose this algorithm takes several hours to complete. To a client, having the most up-to-date set of solutions is important. So, a client can subscribe to the server and receive periodic updates during the algorithm's execution phase. These updates are provided using the ProgressReport object:
#Entity
public class ProgressReport implements Serializable{
private static final long serialVersionUID = 1L;
#Transient
long estimatedMinutesRemaining;
String statusMessage;
Solution currentBestSolution;
}
The Solution class might look like this:
#Entity
public class Solution implements Serializable{
private static final long serialVersionUID = 1L;
double[][] dataArray;
Properties properties;
}
The server persists each ProgressReport to its database. The server does not care to persist estimatedMinutesRemaining, but the client certainly cares about this information. Therefore, the estimatedMinutesRemaining is annotated using #Transient. When the final Solution is located by the algorithm, it is persisted by JPA directly without using a ProgressReport.
If you just want a field won't get persisted, both transient and #Transient work. But the question is why #Transient since transient already exists.
Because #Transient field will still get serialized!
Suppose you create a entity, doing some CPU-consuming calculation to get a result and this result will not save in database. But you want to sent the entity to other Java applications to use by JMS, then you should use #Transient, not the JavaSE keyword transient. So the receivers running on other VMs can save their time to re-calculate again.
In laymen's terms, if you use the #Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attributes of the object within the entity will still be saved.
Im saving the Object to the database using the jpa repository built in save method as so:
userRoleJoinRepository.save(user2);
For Kotlin developers, remember the Java transient keyword becomes the built-in Kotlin #Transient annotation. Therefore, make sure you have the JPA import if you're using JPA #Transient in your entity:
import javax.persistence.Transient
I will try to answer the question of "why".
Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...)
Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way.
While Transient keyword works on an object - as it behaves within a java language, the #Transient only designed to answer the tasks that pertains only to persistence tasks.

Categories