Identify primary key in hibernate - java

Is there any way to identify the Primary key of an entity class in my JSP page.
For Eg: If i call a function, i need to get back the #ID parameter declared in the entity class as return.

It's very obvious how to do this. Assuming that all your entities will look like about the following:
#Entity
public class MyEntity implements Serializable {
private Long id;
#Id
#GeneratedValue(...)
public Long getId() {
}
public void setId(Long id) {
return id;
}
}
you simply write myEntity.getId().

Related

Inheritance in entities, using objectbox

In my code I put some base fields in base abstract class BaseEntity:
public abstract class BaseEntity {
#Id
private long id;
public BaseEntity() {
}
public BaseEntity(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
So, in child class User I am not define an id field:
#Entity
public class User extends BaseEntity {
private String name;
private String login;
private String gender;
private String email;
private String phoneNumber;
private Date registrationDate;
private Date lastActivityDate;
private long systemId;
public User() {
}
...Getters and Setters
}
because it defined in superclass. I don't want to create in every class an id field, and don't want to persist in database BaseEntity class. And I get an error:
Error:[ObjectBox] Code generation failed: No ID property found for Entity User (package:...)
How can I use objectbox with an inheritance?
Polymorphism of entities is not supported at this time, but there is a feature request.
If it helps, you can go for an interface. E.g.:
public interface BaseEntity {
long getId();
}
Note: you could have a setter for the ID, but my personal advice would be to have the id field package private (so ObjectBox has access from generated classes) and not have a setter because it would suggest it's OK to change the ID at any time.
Update: ObjectBox 1.4 introduced entity inheritance (non-polymorphic).
#Oleg Objectbox don't support inheritance in entity class as it will map every entity to a separate table in db and use this #Id variable as unique id to identify a row(entity instance) in that table. Thus #Id variable is must for every entity class.
In general,
for each for Child class to access Parent class variables it have to be either protected or public but in your id is private so change it to either protected it will work.
protected long id;
if you mark it is as protected only the parent and its child class can access it and when you mark it as public any class can access it.
marking it as private means only parent class can access it

Why can I not override and annotate a getter method for entity mapping?

Given this class:
#MappedSuperclass
public abstract class AbstractEntity {
int id;
public void setId(int id) { this.id = id; }
public int getId() { return id; }
// other mappings
}
I want to define an entity:
#Entity
public class SomeEntity extends AbstractEntity {
#Override
#Id // or #OneToOne etc.
public int getId() { return id; }
}
But this fails with a "No identifier specified"
(or a "Could not determine type for") error on SomeEntity. If I remove the getter from the superclass it works. Can't I do this override strategy? Why not, or if yes - how?
Adding
#AttributeOverride(name = "id", column = #Column(name = "ID"))
to the subclass does not change the error.
For you to create an entity class there are requirements that the class must meet. Ex. must have a public/private constructor.
Here is the list of requirements:
http://docs.oracle.com/javaee/5/tutorial/doc/bnbqa.html
Hope this helps.

java hibernate - duplicate column with InheritanceType.JOINED

I want to have superclass and subclass stored in database with InheritanceType.JOINED. But everytime I try to do that, I get an error - Repeated column in mapping for entity: com.inqool.personalpro.entity.QuestionAlgorithm column: id (should be mapped with insert="false" update="false")
here are my entities:
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
public class Question implements Serializable {
private Long id;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
...
}
#Entity
#PrimaryKeyJoinColumn(name="id")
public class QuestionAlgorithm extends Question {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
...
}
When I remove field 'id' from subclass, I get this error: Could not locate table which owns column [id] referenced in order-by mapping
any ideas? thanks.
the problem was in the version of hibernate. In 4.1.7, this is bugged. I changed version to 4.1.4, and everything is working

Hibernate/persistence and singleton pattern

I have a singleton that is to be persisted in database. Other persisted entities should have reference to this singleton. How can it be achieved with Hibernate?
I ended with something not-yet-working like this, faking the single ID of the singleton:
#Entity
#Subselect("select '1' as ID")
class Singleton {
#Id
#Column(name="ID")
private Long getId() { return 1l; }
private void setId(Long id) { }
}
#Entity
#Table(name="ENT")
class MyEnt {
// TODO: how to annotate so that table ENT doesn't need foreign key column
Singleton s;
}
The problem is that I don't want to have a column with foreign key in entities referencing the Singleton - because the singleton is only one and we don't need its ID...
Maybe I am thinking in a wrong way? Maybe it is wrong architecture issue? Did you solve similar issue?
I ended with this:
#Entity
#Subselect("select '1' as ID, * from TABLE")
class Singleton {
#Id
#Column(name="ID")
private Long getId() { return 1l; }
private void setId(Long id) { }
// ... other useful fields persisted in TABLE
}
#Entity
#Table(name="ENT")
class MyEnt implements Lifecycle {
Singleton s;
void onLoad(Session sess, Serializable id) {
this.s = sess.get(Singleton.class, 1l);
}
// etc...
}
If Singleton is only one object, why do you want to map it in other entities?
You may want to load Singleton once and put it in application context. In that case, you may reuse it whenever you need it.

MappedSuperclass - Change SequenceGenerator in Subclass

I'm using JPA2 with Hibernate and try to introduce a common base class for my entities. So far it looks like that:
#MappedSuperclass
public abstract class BaseEntity {
#Id
private Long id;
#Override
public int hashCode() {
// ...
}
#Override
public boolean equals(Object obj) {
// ...
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
However, for every table theres a sequence $entityname_seq which I want to use as my sequence generator. How can I set that from my subclass? I think I need to override #GeneratedValue and create a new SequenceGenerator with #SequenceGenerator.
Yes, it is possible. You can override the default generator name with the #SequenceGenerator annotation.
Base class
#MappedSuperclass
public abstract class PersistentEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "default_gen")
protected Long id = 0L;
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
}
Sequence (SQL)
create sequence role_seq;
Derived class
#Entity
#Table(name = "role")
#SequenceGenerator(name = "default_gen", sequenceName = "role_seq", allocationSize = 1)
public class Role extends PersistentEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#NotNull
#Size(max = 32)
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
This approach worked fine in Hibernate 4.1.x, but it didn't in EclipseLink 2.x.
edit
As per the comment, it seems to be working with EclipseLink 2.6.1-RC1.
In JPA that cannot be done with annotations. Annotation itself cannot be overridden. Entity inherits all the mapping information from MappedSuperClass. There is only two annotations that can be used to redefine mappings inherited from mapped superClass:
AttributeOverride to override column mappings and
AssociationOverride to override join columns / table.
Neither of them helps with GeneratedValue.
With EclipseLink, you can use a Customizer. DescriptorCustomizer interface defines a way to customize all the information about a jpa descriptor (aka a persistent entity).
public class SequenceCustomizer implements DescriptorCustomizer {
#Override
public void customize(ClassDescriptor descriptor) throws Exception {
descriptor.setSequenceNumberName(descriptor.getTableName());
}
}
and in your mapped superclass:
#MappedSuperclass
#Customizer(SequenceCustomizer.class)
public abstract class AbstractEntity implements Serializable {
...
}
I'm writing this as it gets too unreadable as the comment on the accepted answer:
I have a BaseEntity that every other Entity inherits from:
BaseEntity.java:
#MappedSuperclass
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ID")
private Long id;
I then have two Entities User and Order that both inherit from BaseEntity whilst also having the #SequenceGenerator annotation:
User.java:
#SequenceGenerator(name = "SEQ_ID", sequenceName = "SEQ_USER", allocationSize = 1)
public class User extends BaseEntity { ... }
Order.java:
#SequenceGenerator(name = "SEQ_ID", sequenceName = "SEQ_ORDER", allocationSize = 1)
public class Order extends BaseEntity { ... }
It works on H2 at least with 2 Sequences SEQ_USER and SEQ_ORDERS:
select SEQ_USER.nextval from dual;
select SEQ_ORDERS.nextval from dual;

Categories

Resources