#AttributeOverride not working - java

I have the code
#MappedSuperclass
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#XmlAccessorType(XmlAccessType.FIELD)
public abstract class AbstractModel implements Serializable, Comparable<AbstractModel> {
private static final long serialVersionUID = -4479726024447228668L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgen")
private Long id;
...
#MappedSuperclass
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#XmlAccessorType(XmlAccessType.FIELD)
public abstract class AbstractHistoricModel extends AbstractModel {
private static final long serialVersionUID = -3596885940998632065L;
#Column(name = "pblc_id")
...
#Entity
#SequenceGenerator(initialValue = 0, name = "idgen", sequenceName = "abstract_claim_type_seq")
#XmlAccessorType(XmlAccessType.FIELD)
public class AbstractClaimType extends AbstractHistoricModel {
private static final long serialVersionUID = -3840541568639732203L;
#Column(name = "nam")
private String name;
public AbstractClaimType() { super(); }
#Field
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
...
#Entity
#Table("retr_clm_mthd")
#SequenceGenerator….
#FieldModel
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#AttributeOverride(name="nam", column=#Column(name="retr_clm_mthd_nam", length=255))
public class Retrospective extends AbstractClaimType {
...
and when I create the database in memory to test
2013-04-11 14:15:28,445 ERROR (org.hibernate.tool.hbm2ddl.SchemaExport:org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:386)) - HHH000231: Schema export unsuccessful
org.hibernate.tool.hbm2ddl.ImportScriptException: Error during statement execution (file: '/import.sql')
Caused by: java.sql.SQLException: Column not found: RETR_CLM_MTHD_NAM in statement
I look the scriptdb and there is
CREATE MEMORY TABLE RETR_CLM_MTHD(….,NAM VARCHAR(255),….)
Why not retr_clm_mthd_nam?
What is wrong?

You don't have any attribute named "nam" in the superclass. You have one named "name":
private String name;

Related

Duplicate key when inserting with hibernate into inherited classes

Hello I hope you can help me, I have a problem with the inserts in hibernate.
First I have a Person class
#Entity
#Table(name = "persons")
#Inheritance(strategy = InheritanceType.JOINED)
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id_card", columnDefinition = "VARCHAR(13)")
private String idCard;
#Column(name = "name", columnDefinition = "VARCHAR(50) NOT NULL")
private String name;
#Column(name = "last_name", columnDefinition = "VARCHAR(50) NOT NULL")
private String lastName;
}
And I have two classes plus one provider.
#Entity
#Table(name = "providers")
public class Provider extends Person implements Serializable {
private static final long serialVersionUID = 1L;
public Provider() {
// TODO Auto-generated constructor stub
}
}
Customer
#Entity
#Table(name = "customers")
public class Customer extends Person implements Serializable {
private static final long serialVersionUID = 1L;
public Customer() {
// TODO Auto-generated constructor stub
}
}
What happens is that I insert a provider and there is no problem, just like when inserting a client there is no problem, what happens is that when I already insert a person as a client I can no longer insert them as a supplier I get that the key.
What happens is that a person can be a customer and a supplier or an employee at the same time.
ER Diagram

hibernate can not specify a generic property identifier in annotation approach

I create a base class for all entities to every new entity class extend it.
in base class I use annotation for orm, below code:
public class BaseEntity<I> implements IBaseEntity<I> {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", nullable = false)
private I id;
public I getId() {
return id;
}
public void setId(I id) {
this.id = id;
}}
then I create a class as below:
#SuppressWarnings("serial")
#Entity
#Table(name = FoodEntity.TABLE_NAME, schema = "public")
public class FoodEntity extends BaseEntity<Long> {
public static final String TABLE_NAME = "T_Food";
#Column(name = "NAME", unique = true, nullable = false, length = 500)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
but, when I execute a sample to test my classes, I get below exception:
Initial SessionFactory creation failed.org.hibernate.AnnotationException: No identifier specified for entity: FoodEntity
Exception in thread "main" java.lang.ExceptionInInitializerError
at ir.msr.projects.crawler.HibernateUtil.buildSessionFactory(HibernateUtil.java:31)
at ir.msr.projects.crawler.HibernateUtil.<clinit>(HibernateUtil.java:14)
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: FoodEntity
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:266)
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:211)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:731)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:249)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:222)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:265)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
I found my answer, I have to use #MappedSuperclass for BaseEntity Class(Parent Class).
Try to create BaseEntity abstract and anotated Id put to your main class, or use annotation #MappedSuperclass
#MappedSuperclass
public class BaseEntity<I> implements IBaseEntity<I> {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", nullable = false)
private I id;
public I getId() {
return id;
}
public void setId(I id) {
this.id = id;
}
}
or
public abstract class BaseEntity<ID extends Serializable, T extends BaseEntity<ID, T>> {
protected ID id;
public abstract ID getId();
public void setId(ID id) {
this.id = id;
}
}

Java Persistence Composite ID

I'm trying to insert a record with composite primary key, but at the time of saving a new record I get this message:
e = (org.springframework.orm.jpa.JpaSystemException)
org.springframework.orm.jpa.JpaSystemException: Could not set field
value [POST_INSERT_INDICATOR] value by reflection...
#Getter
#Setter
#Entity
#EqualsAndHashCode
#Table(name = "produto")
#IdClass(ProdutoId.class)
public class Produto implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_produto")
private Long idProduto;
#Id
#Column(name = "oficina", insertable = false, updatable = false)
private Long idOficina;
#ManyToOne
#JoinColumn(name = "oficina")
private Oficina oficina;
}
#AllArgsConstructor
#NoArgsConstructor
#EqualsAndHashCode
#Data
public class ProdutoId implements Serializable {
public Long idProduto;
public Long idOficina;
}
#Repository
public interface ProdutoRepository extends JpaRepository<Produto, ProdutoId> {}
Has anyone ever seen a bug like this?
To create composite primary key you can refer this example,
#Entity
#Table(name="testuserrole")
public class UserRole{
#EmbeddedId
private UserRoleId id = new UserRoleId();
public UserRoleId getId() {
return id;
}
public void setId(UserRoleId id) {
this.id = id;
}
#Transient
public long getUserId() {
return id.userId;
}
public void setUserId(long userId) {
id.userId=userId;
}
#Transient
public long getRoleId() {
return id.roleId;
}
public void setRoleId(long roleId) {
id.roleId=roleId;
}
}
#Embeddable
class UserRoleId implements Serializable {
#Column(name = "user_id")
public long userId;
#Column(name = "role_id")
public long roleId;
}

Composite Key with subclass in hibernate

I have a Class system
#Entity
abstract class System{
#Id
int systemId;
//setter and getters..
}
and which is extended by class
#Entity
class PhysicalSystem extends System
{
#Id
int place;
//setter and getters..
}
in need to make the composite key by using the systemId and place
how can i do this.. if i have #Id in both class its throws exception
Initial SessionFactory creation failed.java.lang.ClassCastException: org.hibernate.mapping.JoinedSubclass cannot be cast to org.hibernate.mapping.RootClass
How can i solve this?
Tables:
System{
systemid PK
systemName
}
PhysicalSystem
{
systemId PK
locationId PK
}
In your case, maybe the best solution is a OneToOne mapping:
#Entity
public class PhysicalSystem implements Serializable {
#EmbeddedId
private PhysicalSystemKey key;
#JoinColumns({JoinColumn(name = "key.systemId", referencedColumnName = "ctvId"})
#OneToOne(mappedBy = "physicalSystem")
private System system;
// ...
}
#Embeddable
public class PhysicalSystemKey {
private Long systemId;
private Long locationId;
// ...
}
#Entity
public class System implements Serializable {
#Id
private Long systemId;
#OneToOne(mappedBy = "system")
private PhysicalSystem physicalSystem;
}

java.lang.IllegalStateException: No supertype found on query

I have the following
#Entity
#Table(name = "PROJECTS")
public class Project implements Serializable {
#Id
private Integer SlNo;
#Id
private Long projectNo;
private Date projectDate;
}
and in DAO class
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> countQ = cb.createQuery(Long.class);
Root<Project> empCount = countQ.from(Project.class);
countQ.select(cb.count(empCount));
TypedQuery<Long> countquery = entityManager.createQuery(countQ);// error in this line
I am getting exception java.lang.IllegalStateException: No supertype found in the above line. How can I resolve or workaround this issue? Looks like there is a bug, are there any solution to this?
I am using Hibernate 4.1.0.Final
I have resolved the issue by using #EmbeddedId in Entity class and #Embeddable in Primary Key class.
#Entity
#Table(name = "PROJECTS")
public class Project {
#Column(name = "SL_NO" , insertable = false, updatable = false)
private Integer SlNo;
#Column(name = "PROJECT_NO" , insertable = false, updatable = false)
private Long projectNo;
private Date projectDate;
#EmbeddedId
ProjectPK projectPK;
and Primary Key class
#Embeddable
public class ProjectPK implements Serializable {
#Column(name = "SL_NO")
private Integer SlNo;
#Column(name = "PROJECT_NO")
private Long projectNo;
//with hashCode and equals implementation
for the case Using #EmbeddedId, here is my solution. This code I have written in one class itself, in Entity class.
Class MyEntity - It is my actual Entity class for my table. "OtherFields" are those fields which are not part of primary key.
Class MyEntityPrimaryKeys - It is the class made for my composite key which makes a primary key for my "MyEntity" class. Here ROLLNO and AGE together makes a primary key.
MyEntity.java
#Entity
#Table(name = "myTable")
public class MyEntity extends GenericPersistableEntity implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
MyEntityPrimaryKeys id;//Composite Primary key
//Composite fields can be declared here for getter and setters
#Column(name = "ROLLNO")
private Long RollNo;
//Composite fields can be declared here for getter and setters
#Column(name = "AGE")
private Long age;
#Column(name = "OtherFields"
private Long OtherFields;
//getter and setters comes here
}
#Embeddable
class MyEntityPrimaryKeys implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "ROLLNO")
Long RollNo;
#Column(name = "AGE")
Long age;
#Override
public int hashCode() {
HashCodeBuilder hcb = new HashCodeBuilder();
hcb.append(RollNo);
hcb.append(age);
return hcb.toHashCode();
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MyEntityPrimaryKeys)) {
return false;
}
MyEntityPrimaryKeys that = (MyEntityPrimaryKeys) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(RollNo, that.RollNo);
eb.append(age, that.age);
eb.append(tonMonth, that.tonMonth);
eb.append(tonYear, that.tonYear);
return eb.isEquals();
}
}

Categories