I have one problem with my configuration of play framework, when I insert a new Notification I have received the error. I don´t know why this error occured. Because I extends Model class, Play must generated a new ID for each row.
If you can say to me what is the problem, or other better way to do this, Maybe if I extends the GenericModel and I do the code that is commented like this:
// #Id
// #GeneratedValue(strategy = GenerationType.AUTO)
// public long id;
but if I do this, How I must do the insert a new row?
Thanks a lot!!!!
Error found:
PersistenceException occured : org.hibernate.HibernateException: The database returned no natively generated identity value
This is /app/controllers/WSConfiguracion.java :
if (cliente.valorBateria < filasConfiguracionClientes.get(i).limiteBateria) {
if (!estadoNotificacion.hayNotiBateria) {
// code below generated the error
Notificacion notificacion = new Notificacion(
filasConfiguracionClientes.get(i).imeiadmin,imei, "bateria baja"
).save();
estadoNotificacion.hayNotiBateria = true;
//notificacion.save();
estadoNotificacion.save();
renderText("NOTIFICA BATERIA");
}
} else {
...
}
This is my model.
package models;
import javax.persistence.Entity;
import play.db.jpa.Model;
#Entity
public class Notificacion extends Model {
//#Id
//#GeneratedValue(strategy = GenerationType.AUTO)
//public long id;
//#Id
public long imeiadmin;
//#Id
public long imeiclient;
public String detalleNotificacion;
public Notificacion(long imeiadmin, long imeiclient,String detalleNotificacion) {
this.imeiadmin = imeiadmin;
this.imeiclient = imeiclient;
this.detalleNotificacion = detalleNotificacion;
}
}
I think the error:
PersistenceException occured : org.hibernate.HibernateException: The database returned no natively generated identity value
is occurred because there is no sequence in your database. If you extends Model class for your model and you are on Development mode, Play!Framework automatically generated sequence on your database named hibernate_sequence. The sequence is used to generated ID for your model. You may check your database to ensure that sequence is present.
If the hibernate_sequence is present, you can insert data like you do before :
Notificacion notificacion = new Notificacion(
filasConfiguracionClientes.get(i).imeiadmin,imei, "bateria baja"
).save();
then, the error above should be resolved.
Note:
I am referring this answer if you used PostgreSQL database. If you use other database such as MySQL, you should define AUTO_INCREMENT on ID column as the sequence definition.
Update - I have tried this for H2 DB setting
Using H2 database as configure in application.conf :
# Development mode
application.mode=dev
# Set simple file written database (H2 file stored)
db=fs
# JPA DDL update for development purpose only
jpa.ddl=update
The controller :
public static void test15878866() {
// force to insert dummy data
Notificacion notificacion = new Notificacion(
1L, 2L, "This is new notificacion"
).save();
renderText(notificacion.detalleNotificacion);
}
The model :
#Entity
public class Notificacion extends Model {
public long imeiadmin;
public long imeiclient;
public String detalleNotificacion;
public Notificacion(long imeiadmin, long imeiclient,String detalleNotificacion) {
this.imeiadmin = imeiadmin;
this.imeiclient = imeiclient;
this.detalleNotificacion = detalleNotificacion;
}
}
I found the mistake!! I have only had to add super(); inside the constructor.
Thanks for all, iwawiwi.
The model :
#Entity
public class Notificacion extends Model {
public long imeiadmin;
public long imeiclient;
public String detalleNotificacion;
public Notificacion(long imeiadmin, long imeiclient,String detalleNotificacion) {
super();
this.imeiadmin = imeiadmin;
this.imeiclient = imeiclient;
this.detalleNotificacion = detalleNotificacion;
}
}
Related
I have an Enum class which has some values.
We've decided to remove one of these values and its all implementation from the code.
We dont want to delete any records from DB.
My Enum class is something like this:
public enum CourseType {
VIDEO("CourseType.VIDEO"),
PDF("CourseType.PDF"),
QUIZ("CourseType.QUIZ"),
SURVEY("CourseType.SURVEY"),
POWERPOINT("CourseType.POWERPOINT") //*this one will be removed*
...
}
My Course Entity:
#Entity
#Table(name = "CRS")
public class Course {
#Column(name = "COURSE_TYPE")
#Enumerated(EnumType.STRING)
private CourseType courseType;
#Column(name = "AUTHOR")
private String author;
....
#Override
public CourseType getCourseType() {
return courseType;
}
#Override
public void setCourseType(CourseType courseType) {
this.courseType = courseType;
}
....
}
After I removed the Powerpoint type from the Java Class and tried to fetch some values from the DB,
I get a mapping error for the removed type.
I have a code like this:
Course course = courseService.get(id);
If I gave a course id which its type is 'POWERPOINT' in the database,
the method gets the following error:
java.lang.IllegalArgumentException: Unknown name value [POWERPOINT]
for enum class [com.tst.enums.CourseType] at
org.hibernate.type.EnumType$NamedEnumValueMapper.fromName(EnumType.java:461)
at
org.hibernate.type.EnumType$NamedEnumValueMapper.getValue(EnumType.java:449)
at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107) at
org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127) at
org.hibernate.type.AbstractType.hydrate(AbstractType.java:106) at
org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2912)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)
Is there any way when I try to retrieve a query result from DB,
hibernate will not fetch if that records' course_type column doesn't match with the any of the enum values in the code?
Do I have to use some kind of filter?
You can try use annotation #filter
#Filter(name = "myFilter", condition = "courseType <> 'CourseType.POWERPOINT'")
and enable it
session.enableFilter("myFilter")
If you can't use filters,
something like the following should work:
Add POWERPOINT back into the enum.
Add a deleted flag to the POWERPOINT enum value.
After the course list is loaded, remove courses that have a deleted courseType value.
New CourseType enum:
public enum CourseType
{
VIDEO("CourseType.VIDEO", false),
POWERPOINT("CourseType.POWERPOINT", true);
private boolean deletedFlag;
public CourseType(
existingParameter, // do whatever you are currently doing with this parameter
deletedFlagValue)
{
// code to handle existing parameter
deletedFlag = deletedFlagValue;
}
This question already has answers here:
Hibernate Auto Increment ID
(7 answers)
Closed 7 years ago.
I am using Spring 4 and have the following set up for my data model:
#Entity
#Table(name ="InstanceData")
public class InstanceData {
private Long instanceDataId;
private Long heapUsed; //in bytes
private Long heapMax; //in bytes
#Id
#Column(name="InstanceDataId")
#SequenceGenerator(name="DataSeq", sequenceName="DATA_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="DataSeq")
public Long getInstanceDataId() {
return instanceDataId;
}
public void setInstanceDataId(Long id) {
this.instanceDataId = id;
}
#Column(name="HeapUsed")
public Long getHeapUsed() {
return this.heapUsed;
}
public void setHeapUsed(Long heapUsed) {
this.heapUsed = heapUsed;
}
#Column(name="HeapMax")
public Long getHeapMax() {
return this.heapMax;
}
public void setHeapMax(Long heapMax) {
this.heapMax = heapMax;
}
I let Hibernate create the schema automatically. I then try the following SQL (on the H2 db):
insert into instance_data (heap_used, heap_max) values (100, 100);
The error I get is: Error: NULL not allowed for column "INSTANCE_DATA_ID";
SQLState: 23502
My question is why doesn't it auto generate the primary key? How should I change my data model configuration so that the primary key is auto generated (starting at 1)? Thanks for your help.
I would like to understand why even though I am using the #GeneratedValue annotation, the primary key is not auto generated.
Why are you using raw SQL? Just create a new object of class InstanceData, set fields heapUsed and heapMax and use Hibernate's save() method. Then id would be generated automatically.
Annotate id getter like this
#Id
#Column(name="InstanceDataId")
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getInstanceDataId() {
return instanceDataId;
}
and if you dont want to create raw sql scheme you can build up something similar to this (ofcourse it works only using inmemory db)
#Component
#Transactional
public class DummyDbCreator {
private SomeService someService;
#Autowired
public DummyDbCreator(SomeService someService) {
this.someService = someService;
}
#PostConstruct
public void initialInserts() {
Some some = new Some();
// some more entites
// ...
// and other entites
someService.save(some);
}
}
Add this class to some component scanned package or just declare it as a bean in your configuration
I faced with a very strange behavior in my web app with spring 3 and hibernate-core 3.5.1-Final.
For simplicity i provide my code..
if(ripid!=null){ //Parameter
Appuntamento apDaRip = appuntamentoService.findById(ripid);
if(apDaRip.getIdpadre()!=null){
apDaRip.setNota("RIPROGRAMMATO n."+ripid.toString()+"\n"+apDaRip.getNota());
apDaRip.setIdpadre(apDaRip.getIdpadre());
}else{
apDaRip.setNota("RIPROGRAMMATO n."+ripid.toString()+"\n"+apDaRip.getNota());
apDaRip.setIdpadre(ripid);
}
try{
apDaRip.setOrarioinizio(null);
apDaRip.setDurata(null);
//apDaRip.setIdappuntamento(null);
}catch(Exception e){e.printStackTrace();}
map.put("appuntamento", apDaRip);
}
di = datiintranetService.findById(DatiintranetService.PASS_X_INTERVENTI);
map.put("passinterventi", di.getBoolean());
The idea behind is to use some data of an object "Appuntamento" for produce a new one.
So i'm going to change some value and before send the object to my view (jsp) i fetch other data by calling findbyid. This cause an update to the Appuntamento object... Off course i don't want this behavior. Someone can have an explanation of this?
Edit-1
Here's the Dao
#Transactional
public class DatiintranetService {
private DatiintranetDAO datiintranetDAO;
public void setDatiintranetDAO(DatiintranetDAO datiintranetDAO) {
this.datiintranetDAO = datiintranetDAO;
}
public DatiintranetDAO getDatiintranetDAO() {
return datiintranetDAO;
}
public Datiintranet findById(Integer id) {
return datiintranetDAO.findById(id);
}
}
and For Appuntamento class I provide to you a snapshot
#Entity
#Table(name = "appuntamento", schema = "public")
public class Appuntamento implements java.io.Serializable {
#Id
#SequenceGenerator(name="appuntamentoID", sequenceName="appuntamento_idappuntamento_seq",allocationSize =1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="appuntamentoID")
#Column(name = "idappuntamento", unique = true, nullable = false)
public Integer getIdappuntamento() {
return this.idappuntamento;
}
}
Edit-2
IF i move thoese two row above the if statement no update occur.
di = datiintranetService.findById(DatiintranetService.PASS_X_INTERVENTI);
map.put("passinterventi", di.getBoolean());
If you query for an entity and change the entity, the default behavior is to persist those changes via an update to the database. This is usually what you want to happen, but obviously not in all cases.
If you want to avoid the update, you need to detach the entity by calling session.evict(apDaRip) where session is a reference to the hibernate session (see Session.evict()). You probably want to evict the entity right after you get it (immediately following the call to findById).
I'm using WAS 8.0.0.5, which means I'm using OpenJPA 2.1.2-SNAPSHOT. I'm using the Criteria Query API and Canonical Metamodels. I need to access an Oracle View. The View has 1 column named GUID, which uses this SQL:
select sys_guid() from dual;
to populate itself.
I'm using RAD 8.5.1 and its JPA features to generate my entities based off what's in the db.
Here's my entity:
#Entity(name="vguid")
#Table(name="V_GUID")
public class VGuid implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(length=32)
private String guid;
public VGuid() {}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
}
RAD is underlining #Column and providing this error:
Column "guid" cannot be resolved on table "V_GUID"
ಠ_ಠ
I know that #Column(length=32) works because I use it works within another Entity that reads a GUID from an Oracle table (The View is used to populate the GUID field of this other table).
How can I resolve this error?
O.K....so, I closed RAD and reopened the project. The error disappeared. Arghhh!
I use play framework !! But when I run my project it give me this
org.hibernate.exception.SQLGrammarException: could not execute query
who can help me ?
this is my model:
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import play.db.jpa.Model;
#Entity
#Table(name="GxkAccount")
public class GxkAccount extends Model {
private String Account;
private String Psw;
public String getAccount() {
return Account;
}
public void setAccount(String account) {
Account = account;
}
public String getPsw() {
return Psw;
}
public void setPsw(String psw) {
Psw = psw;
}
public static List<GxkAccount> GetList()
{
List<GxkAccount> infoList=GxkAccount.findAll();
return infoList;
}
}
You are completely missing the mapping annotations for the properties of your class.
P.S. Please try to follow the Java naming conventions
Using mysql, we also faced this type of issue. We found in play framework application.conf:
jpa.dialect=org.hibernate.dialect.PostgreSQLDialect
we replaced this with
jpa.dialect=org.hibernate.dialect.MySqlDialect.
This solved the problem. If you are facing this issue you can try out this configuration setting.
We also faced the same issue. We were having create in the xml and #GeneratedValue on the id column. The resolution is remove the #GeneratedValue annotation and put the value of the id manually, also the jpa takes long by default so give long value e.g 1l.
To do the auto generation follow some another rule.
The issue around the JPA related auto generated Id is resolved as below:
Modify the Person.java model class to have the following annotations for the Id attribute:
#Id
#TableGenerator(name="TABLE_GEN",table="T_GENERATOR",pkColumnName="GEN_KEY",pkColumnValue="TEST",valueColumnName="GEN_VALUE",initialValue=1,allocationSize=1)
#GeneratedValue(strategy=GenerationType.TABLE, generator="TABLE_GEN")
public Long Id;
This will create a table in the mysql schema called T_GNERATOR which will have the tracking of the next value for Id and JPA over hibernate knows how to retrieve this value. The assumption is that the initial value for the Id is 1 and it is incremented by 1 on each new insertion into it as is obvious from the attributes of the annotation.