I'm getting stuck with this error in a week. Could anyone explain why I'm getting this error and how to solve it?
I have an Entiry class Version and I want to return the Id after persist an Version entity object. But I'm getting this error:
Exception [EclipseLink-71] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while setting the value of the instance variable [id] to the value [38].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[id-->Version.ID]
Descriptor: RelationalDescriptor(varick.rap.demo.entities.VersionPK --> [DatabaseTable(Version)])
This is my full code:
factory = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
entity = factory.createEntityManager();
entity.getTransaction().begin();
Version version = new Version();
version.setVersion(getNext(this.version));
version.setProjectID(projectID);
entity.persist(version);
entity.flush();
System.out.println("Version Id: " + version.getId());
entity.getTransaction().commit();
Version entity class(this class is using an #EmbeddedId):
#Entity
#Table(name="Version")
public class Version implements Serializable {
#EmbeddedId
private VersionPK id;
#Column(name="Version")
private String version;
#Column(name="ProjectID")
private int projectID;
public Version() {
}
public VersionPK getId() {
return this.id;
}
//get and set methods here
VersionPK class:
#Embeddable
public class VersionPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
public VersionPK() {
}
//get and set method here
the primary key is not set. maybe you should do like this :
VersionPK pk = new VersionPK();
pk.setId("****");
Version version = new Version();
version.setId(pk);
version.setVersion(getNext(this.version));
version.setProjectID(projectID);
entity.persist(version);
entity.flush();
System.out.println("Version Id: " + version.getId());
entity.getTransaction().commit();
Related
I my project I have to class
#Entity
#Table(name = "asset")
public class Asset extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "last_position")
private Position lastPosition;
/**contructor, getter, setter method, other field etc..**/
}
and another class
#Entity
#Table(name = "position")
#EntityListeners(EntityChangeCallback.class)
public class Position extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(mappedBy="lastPosition")
private List<Asset> assets;
/**contructor, getter, setter method, other field etc..**/
}
Data Access Object like this
public abstract class BaseDaoImp<E extends Indexable> implements BaseDao<E> {
#PersistenceContext
protected EntityManager em;
/**some thing else**/
#SuppressWarnings("unchecked")
public List<E> list() {
Query qry = em.createQuery("from " + getType().getSimpleName() + " u");
return qry.getResultList();
}
}
when i run the code. I get the error
Caused by: java.lang.IllegalArgumentException:
org.hibernate.QueryException: could not resolve property:
lastPositionId of: com.abc.server.db.entity.Asset [FROM
com.abc.server.db.entity.Position pos WHERE pos.deviceId IN
('100 000000001000','100000000001001','100000000001002') AND pos.id IN
(SELECT asset.lastPositionId FROM com.tma.ats.am.server
.db.entity.Asset asset)]
I found the problem is Hibernate generate query with field name lastPositionId Instead of lastPosition. I change field name from lastPosition to lastPositionId. Everything work Ok. But I read many example on web and from my own project. All other field can map #ManyToOne Ok and they don't need Postfix Id. How can i make above code work with field name lastPosition (not lastPositionId) ?
Thank for any help.
there is a property in your jpa xml configuration file called hibernate.hbm2ddl.auto. Change its value to create or create-drop to apply new changes.
I want to save Tesis class using entityManager.persist() method but I get following error.
Caused by: javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: thymeleafexamples.layouts.acenta.Acenta.
#Entity
public class Tesis {
public Tesis(){
}
public Tesis(String adi, Acenta acenta) {
this.adi = adi;
this.acenta = acenta;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotEmpty
private String adi;
#NotEmpty
#ManyToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
#JoinColumn(name="acenta_id")
private Acenta acenta;
//GETTERS AND SETTERS
}
/////////////////////////////////////////////////////////////////////
#SuppressWarnings("serial")
#Entity
public class Acenta implements java.io.Serializable {
public Acenta(String adi) {
this.adi = adi;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotEmpty
private String adi;
#OneToMany(mappedBy="acenta")
private Set<Tesis> tesiss;
}
According to Hibernate Validator's API org.hibernate.validator.constraints.NotEmpty annotation
"asserts that the annotated string, collection, map or array is not
null or empty"
Based on the above definition Acenta type is not a valid type to check. You may consider using javax.validation.constraints.NotNull annotation instead as it's valid for all types and moreover not vendor specific.
After I persist an object and commit like this:
Version version = new Version();
version.setVersion(getNext(this.version));
version.setProjectID(projectID);
em.persist(version);
em.getTransaction().commit();
I want to get the ID(Primary Key) by this code line:
Object id = factory.getPersistenceUnitUtil().getIdentifier(version);
I can get the Version and ProjectID but the ID is null. The ID is auto generated but still return null. I tried to implement #GeneratedValue(strategy=GenerationType.IDENTITY) in my entity class but nothing change. Any solution for me?
EDIT WITH MORE CODE
Version Entity: this is using an EmbededId
#Entity
#NamedQuery(name="Version.findAll", query="SELECT v FROM Version v")
#Table(name="Version")
public class Version implements Serializable {
#EmbeddedId
#GeneratedValue(strategy=GenerationType.SEQUENCE)
private VersionPK id;
#Column(name="Version")
private String version;
#Column(name="ProjectID")
private int projectID;
Embeddable class:
#Embeddable
public class VersionPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="ID")
private int id;
public VersionPK() {
}
You have to use flush() after commiting to be able to get the id:
em.persist(version);
em.getTransaction().commit();
em.flush();
Then just use getter to have the id:
Object id = version.getId();//getId() is the getter of the id in your entity.
See the answer here.
I have the following Entity structure:
public abstract class BaseEntity {
private int _version;
public BaseEntity() {
}
#Version
#Column(name = "oplock", nullable = false)
private int getVersion() {
return _version;
}
#SuppressWarnings("unused")
private void setVersion(final int version) {
_version = version;
}
//some other code goes here....
}
the concrete Entity:
#Table(name="my_table", schema="public",
uniqueConstraints=#UniqueConstraint(columnNames={"username", "attribute"})
)
public class MyEntity extends BaseEntity implements java.io.Serializable {
private int id;
private String username;
private String attribute;
private String op;
private String value;
public MyEntity() {
}
//some code goes here ....
}
Now, I select from the database an entity of MyEntity type, lock it with entityManager.lock(myEntityInstance, LockModeType.OPTIMISTIC);, modify it, and persist modifications. The thing that I expect to get is to have oplock column's value incremented (oplock is the version column), but it is untouched.
Question: Does it behave right or am I missing something? I think the right behavior would be that the oplock's value would be incremented.
Edit: After I switched from hibernate 3.6 to hibernate 4.1, I still get the same behavior.
Finally I solved my problem:
I put only #MappedSuperclass annotation above BaseEntity class. For more details you can read here.
I am trying to do mapping in JPA.
#Entity
public class Auction {
#Id
private Integer auctionId;
#OneToMany(mappedBy="auctionId")
#MapKey(name="auctionParamId")
private Map<AuctionParam, AuctionParamValue> values;
}
#Entity
public class AuctionParam {
#Id
private Integer auctionParamId;
private String description;
}
#Entity
public class AuctionParamValue {
#EmbeddedId
private AuctionParamValuePK pk;
private String value;
}
#Embeddable
public class AuctionParamValuePK {
#ManyToOne
#JoinColumn(name="auctionId")
private Auction auction;
#ManyToOne
#JoinColumn(name="auctionParamId")
private AuctionParam auctionParam;
}
Showing an error:-
.Error-Details:-Exception Description:
Entity [class
com.eaportal.domain.AuctionParamValue]
uses [class
com.eaportal.domain.AuctionParamValuePK]
as embedded id class
whose access-type
has been determined as [FIELD].
But
[class
com.eaportal.domain.AuctionParamValuePK]
does not define any [FIELD]. It is
likely that you have not provided
sufficient metadata in your id class
[class
com.eaportal.domain.AuctionParamValuePK].
If you come up with a solution please let me know.
Thanks in Advance
Tushar
You cannot use an EmbeddedId with relationships. Use an IdClass.
#Entity
#IdClass(AuctionParamValuePK.class)
public class AuctionParamValue {
#Id
#ManyToOne
#JoinColumn(name="auctionId")
private Auction auction;
#Id
#ManyToOne
#JoinColumn(name="auctionParamId")
private AuctionParam auctionParam;
#Basic
private String value;
}
public class AuctionParamValuePK {
private int auction;
private int auctionParam;
}
I think there are some errors in your Auction class. This is how I think it should look
#Entity
public class Auction {
#Id
private Integer auctionId;
#OneToMany(mappedBy="auction") // not auctionId
#MapKey(name="auctionParam") // not auctionParamId
private Map<AuctionParam, AuctionParamValue> values;
}
(The annotation values have to correspond with fields (or properties), not with columns)