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/
Related
I have a model class that is mapped to a postgres database using hibernate. My model class is:
CheckRes.java
package com.example.demo.model;
import javax.persistence.Id;
import javax.persistence.*;
#Entity
#Table(name="checkers",schema = "public")
public class CheckRes {
public long getID() {
return ID;
}
public void setID(long ID) {
this.ID = ID;
}
public String getCheck() {
return check;
}
public CheckRes() {
}
public void setCheck(String check) {
this.check = check;
}
#Id
private long ID;
public CheckRes(String check) {
this.check = check;
}
#Column(name="check")
private String check;
}
application.properties
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.hibernate.ddl-auto = update
The following table is already existing in db with create script as:
CREATE TABLE public."checkers"
(
"ID" bigint NOT NULL,
"check" character varying(20),
CONSTRAINT "checkers_pkey" PRIMARY KEY ("ID")
)
TABLESPACE pg_default;
ALTER TABLE public."checkers"
OWNER to postgres;
Later when I am trying to invoke the controller get method from a postman , I am getting the following error.
org.postgresql.util.PSQLException: ERROR: column checkres0_.id does not exist
Position: 8
If the table doesnt exist then hibernate automatically creates a table with '_' and there are no errors. But I dont need the hibernate to create any tables. It just needs to use the existing ones for CRUD operations,is there any other naming convention I am missing?
Generally, this is a good practice to follow java naming conventions. According to that you should rename ID field to id.
And then as was noticed by #User-Upvotedon'tsayThanks and #a_horse_with_no_name you should use #Column with quotes:
#Id
#Column(name="`ID`")
private long id;
Also your getters and setters should follow JavaBean conventions. So, for the above field you should have the following getter and setter:
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
}
Hi im trying to do a persist but looks like if one of the atributes never was set but, just before do the persist I print the value and is set. I´m working with postgrest
My persist metod
public void saveText(Document document){
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
System.out.println(document.getText());
System.out.println(document.getId());
try {
session.beginTransaction();
session.persist(document);
session.getTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
My object to pesist
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import br.com.symsar.sysged.acessobd.AccesData;
#Entity
#ManagedBean
#SessionScoped
#Table(name = "documents", schema = "public")
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "\"id\"")
private int id;
#Column(name = "\"text\"")
private String text;
public void persist() {
AccesData access = new AccesData();
access.saveText(this);
}
/**
* #return the text
*/
public String getText() {
return text;
}
/**
* #param text
* the text to set
*/
public void setText(String text) {
this.text = text;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
Sql query showed by hibernate
Hibernate: insert into public.documents ("id", "text") values (null, ?)
This is the error:
ERROR: ERRO: Null value in the column "id" violates not-null constraint
Field id have JPA annotation #Id in your entity class. It's mean's that it can't be null. Try insert value without id parameter:
Hibernate: insert into public.documents ("text") values (?)
Try removing annotations
#ManagedBean
#SessionScoped
I resolved not using session factory now I´m using entity manager, when I made this change works.
Thanks all for the ideas
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.
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).