I’m a bit confused about how getters and setters in JPA annotated POJO classes interact with a proposed MySQL database via Hibernate.
I understand that you can have, for example, the following:
@Entity
@Table(appliesTo = "users")
public class UserDM implements UserIF, Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String name;
private Date createDate;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String n) {
name = n;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(final long time) {
createDate = new Date(time);
}
}
-
Why is the auto ID generation strategy associated with the Getter?
-
How does that method actually auto-incremeent the ID when a new user is stored?
-
What is the order of operations? The POJO is filled via setters (or maybe a constructor?) and then the info is acquired by hibernate via getters and then stored into the db?
-
Is it a good idea to have my “getCreateDate” method return a date, or is it best to have the fields in pojos map to MySQL-friendly fields? If I wanted to get a Date object from a timestamp ms value, would the best way to do that be to use a transient mapped function?
This is a matter of taste, most of the time. You can put the annotations on fields or accessors (getters), depending on how you prefer, as long as it’s consistent (always on methods, or always on properties). By setting it to the property, Hibernate will use reflection to get access to the property (it’s not as bad as it sounds). By setting it to the method, Hibernate will use it instead of reflection.
Not sure at which level of details you want the answer, but to keep it short:
Auto will use the best auto-increment strategy for the database server you are using. It could be “identity” for Sybase/SQLServer, it could be “sequence” for Oracle-like or it could be “auto increment” for MySQL. Common to all those cases is the fact that Hibernate will not know the ID until the database generates it. After triggering an “insert”, Hibernate will use a standard JDBC method to access the “generated id”
Again, I don’t know which level of details you want this, but yes, that’s the order. You fill the POJO and you call the persist method on the EntityManager, passing this POJO as parameter. Hibernate will then call the getters (or access the properties) and will send this data to the database.
Try to keep your application “database agnostic”. So, don’t make it “mysql friendly” if you don’t really need. In general, using a java.util.Date in a field mapped with
@Temporal(TIMESTAMP)would do, but if you need more “powerful” date/time objects, like Joda-time, you can also use it (as long as you tell Hibernate how to use it).