PostgreSQL network types in Hibernate - java

I want to use Postgresql network data type of mac address (macaddr) in Hibernate ORM. How could I map macaddr type to a entity class property? What is the best way of doing so? I never used non standard SQL types in Hibernate
Thx

Mac address is a String. If it's a #OneToOne relationship between the mac address and its user, then you don't have to make an entity class out of simple strings, just include it as a field on whatever entity needs it, like so:
private String macAddress;
If the same mac address is used by multiple entities and you want to reuse the value (normalize), then you'd make an entity like this:
package com.acme.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class MacAddress implements Serializable {
private static final long serialVersionUID = 1l;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

I just solve a problem like this,so I insert and get row from DB postgresql 9 successfully. The solution explained completely is in this link network postgres types on hibernate

Because of the mac-address is never totaly validated, there is no Standard-Type in Java. You can use
#ColumnTransformer(read="CAST(mac AS varchar)", write="CAST(? AS macaddr)") String
instead to read/write it as String.

Related

gcloud Data store Key to use UUID

I am new with gcloud DataStore Key. I was wondering how I can define my Key to use UUID ?
For example in the Instrument.java class below, how to make sure the Key object use UUID ?
import java.util.Objects;
import com.google.cloud.datastore.Key;
import org.springframework.cloud.gcp.data.datastore.core.mapping.Entity;
import org.springframework.data.annotation.Id;
#Entity
public class Instrument {
#Id
Key instrumentId;
private String type;
public Instrument(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
}
You are specifying it right.
As defined in the documentation, A data class must have one and only one field dedicated to storing the primary key of the corresponding datastore entity. So, the key is the UUID of the Datastore Entity.
In this case, since you are using the Spring framework org.springframework.cloud.gcp, to define the which attribute is the key, you have to specify it in the way specified in the Datastore Spring framework documentation is to use #Id.
import org.springframework.cloud.gcp.data.datastore.core.mapping.Entity;
import org.springframework.data.annotation.Id;
#Entity
public class Singer {
#Id
String singerId;
String name;
}

Unable to change revinfo table name in Hibernate Envers

I went to the documentation (http://docs.jboss.org/envers/docs/#revisionlog) there it was written that if we annonate an entity with #RevisionEntity then Hibernate will not create default revinfo table by its own instead it will map the entity which is annotated with #RevisionEntity. I tried still its createing default table named as revinfo and not custom named table as RevisionTable.
Following is the code :
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.envers.RevisionEntity;
import org.hibernate.envers.RevisionNumber;
import org.hibernate.envers.RevisionTimestamp;
#RevisionEntity
public class RevisionTable {
#Id
#GeneratedValue
#RevisionNumber
private int id;
#RevisionTimestamp
private long timestamp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
I am not understanding where i am going wrong. As i am new to Hibernate Envers, it will be helpfull if explain the solution in detail.
Your revision entity needs to also contain these annotations:
#Entity
#Table(name="REVISIONS_TABLE_NAME")
and it needs to be scanned by hibernate like any other entity. Please refer to the documentation, this was specified there: http://docs.jboss.org/envers/docs/

GenerationType.AUTO vs GenerationType.IDENTITY in hibernate

Currently, we are using MySQL as a database and we use
#Generated Value(strategy = GenerationType.IDENTITY)
It's working perfectly in certain situations we need to migrate our database to Oracle at that time it's not working properly. If anyone knows what's the actual difference is present behind this and how it's working?
Quoting Java Persistence/Identity and Sequencing:
Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.
so I prefer to use SEQUENCE instead
Sequence objects use special database objects to generate ids. Sequence objects are only supported in some databases, such as Oracle, DB2, and Postgres. Usually, a SEQUENCE object has a name, an INCREMENT, and other database object settings. Each time the .NEXTVAL is selected the sequence is incremented by the INCREMENT.
Example :
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="EMP_SEQ")
#SequenceGenerator(name="EMP_SEQ", sequenceName="EMP_SEQ", allocationSize=100)
private long id;
...
}
How could it "work properly" (you don't define basic info like what you mean by that) with Oracle ? I don't see the relevance of AUTO to your question - that simply lets an implementation choose what it wants to use.
"IDENTITY" (as per JPA javadocs and spec - what you should be referring to) means autoincrement. There is no such concept in Oracle, yet there is in MySQL, SQLServer and a few others. I would expect any decent JPA implementation to flag an error when even trying such a thing.
Oracle would allow "SEQUENCE", or "TABLE" strategies to be used however
Im using JPA and Oracle 11g, the solution that worked for me is the following
package com.example.springsocial.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "rol", uniqueConstraints = {
#UniqueConstraint(columnNames = "name")
})
public class Rol {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="rol_sequence")
#SequenceGenerator(name="rol_sequence", sequenceName="rol_sequence", allocationSize=100)
private Long id;
#Column(nullable = false)
private String name;
private Date createdAt;
#Column(nullable = true)
private Date updatedAt;
#Column(nullable = true)
private Integer createdBy;
#Column(nullable = true)
private Integer updatedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Integer getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(Integer updatedBy) {
this.updatedBy = updatedBy;
}
}

Hibernate - why put a column name before getter instead of variable?

If we make a column Id which corresponds to id of User, then why don't we put it near the variable id instead of the getter for id ? I got the answer to that here - Where to put hibernate annotations?.
But, because my book put it near the getter, it looks like some class will need to access this object via getter to serialize/persist it to a database. What is this class and how is does it perform the persistence ? Do I call its methods to do the persistence ?
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User {
private Long id;
private String password;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Hibernate will use reflection to find the appropriate methods or fields on your class to read. This is why Hibernate is able to read private fields.
The code that does this reflection is called from session.save(Object object).

Is it possible to set Hibernate's "default" variable name mapping?

I'm looking for a way to set the "default" mapping that Hibernate applies to a variable name in a Java object to query it against the database. At the moment we are using the inline javax.persistence markup to manually set column names, but since we have a rigid naming policy for our database it would be nice to be able to just skip on the manual naming and let Hibernate do the mapping. However, at the moment this doesnt work nice at all with anything save for local, non-primary key fields.
At the moment, Hibernate seems to be set to map non-foreign keys to just their name (see "foo" in the below example class), and foreign-keys to "variableName_ReferencedTable_Id" (see "bar" in the below example class). We would like non-foreign keys to stay as they are, except for the variable marked #id, which we would like to be mapped to "TableName_Id", and we would like foreign keys to be mapped to "variableName_Id". Is this even possible, or do we just have to put up with manual mapping?
package testPackage.test
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Table1 {
private int id;
private int localVariable;
private int foreignKeyVariable;
// Constructor here somewhere
// Without a #Column( name="Table1_Id" ), this comes out as "id".
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// This works fine, being a local field.
public int getLocalVariable() {
return localVariable;
}
public void setLocalVariable(int LocalVariable) {
this.localVariable = localVariable;
}
// Withou a #JoinColumn( name="foreignKeyVariable_Id" ) , this comes out as "foreignKeyVariable_Table2_Id".
#ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
#JoinColumn() // Not sure if this would even be necessary at all. Happy to leave it out if possible.
public int getForeignKeyVariable() {
return foreignKeyVariable;
}
public void setForeignKeyVariable(int foreignKeyVariable) {
this.foreignKeyVariable = foreignKeyVariable;
}
}
(copied from comment)
Hibernate does have the concept of NamingStrategy, but it's not sensitive to whether than object is a PK or a normal column, so that's not going to be of any use.

Categories