Using Sequence in non Id field In jpa and Sql Server - java

My JPA Entity contiens a non id field named counter, the value of this field is getted from Sql server sequence.
How can i represente this requirement in my JPA mapping of the entity ?
I note that i can't add/modify the dabatabase objects ( triger/ function / procedure ), the solution must be bassed on JPA
Thanks !

JPA does not define #GeneratedValue on non-ID fields. However some JPA implementations (e.g the one I use DataNucleus JPA) do allow it, hence if using one of those implementations then you could just annotate the field as SEQUENCE.

Related

Hibernate entity only one column, no name

I want to map one column, without using a column name.
I am using a count entity, and the want to use mulple different queries with the same entity :
#Entity
public class CountDTO extends Number {
#Id
// below causes an error in my test, hsql not same syntax
#Column(name = 'COUNT')
private Long count;
In my prod (oracle) database I can just do select count() as COUNT from ... however, the same syntax doesn't work using hypersql in-memory db ?
Is their an oracle/hsql compatible way to map a single column alias in HQL ?
Your issue is that COUNT is a reserved keyword for HSQL, but not for Oracle.
According to the HSQL documentation, it might still be possible to use COUNT as identifier, if you either
Mask it as described in the Hibernate documentation or in the JPA spec (cf. chapter 2.13 from the JPA 2 spec; you'll need to accept their license agreement). Note that the JPA spec speaks of double quotes whereas the Hibernate documentation mentions backticks (which will be converted to the appropriate character according to the database dialect in use).
From the hibernate documentation:
You can force Hibernate to quote an identifier in the generated SQL by
enclosing the table or column name in backticks in the mapping
document. Hibernate will use the correct quotation style for the SQL
Dialect. This is usually double quotes, but the SQL Server uses
brackets and MySQL uses backticks.
From the JPA 2 spec:
Using annotations, a name is specified as a delimited identifier by
enclosing the name within double quotes, whereby the inner quotes are
escaped, e.g., #Table(name="\"customer\"").
Configure HSQL to allow it by executing SET DATABASE SQL NAMES FALSE (however, this should already be the default setting and it will only allow "the use of most keywords", not all - edit: COUNT will still be disallowed as per documentation)
My recommendation would be to avoid using identifiers if possible as you never know what problems may arise elsewhere (e.g. one might think Hibernate would be able to mask keywords itself) and use something like COUNT1 instead as column name.
The above part of the JPA spec also explains why Hibernate does not mask the name itself:
By default, the names of database objects must be treated as
undelimited identifiers and passed to the database as such.
The JPA spec also mentions a <delimited-identifiers/> option "to specify that all database identifiers in use for a persistence unit be treated as
delimited identifiers", but this seems to be only usable with an XML mapping file.

How to get selection with ManyToMany relationship in the Play framework [duplicate]

I have a simple jpa entity 'ApplicationForm' with a one to many list in it:
#OneToMany(cascade=CascadeType.REMOVE, mappedBy="textQuestion")
private List<Dictionary> questions;
The variable Dictionary contained in ApplicationForm is just another plain entity with just the text of the question.
The corresponding database table mapped by Dictionary is:
'locale' 'text' 'formId'
en my question 123
it mia domanda 123
I was wondering if it's possible with jpa or hibernate, to build a query for retrieving an ApplicationForm entity with a Dictionary for a specific locale, for example 'it' only.
That would be easy enough to do with standard sql, but I cannot translate in hql.
If not possible, could you suggest an alternative way ? I have tried to manually iterate the Dictionary questions list and remove the not required locale, but is not really elegant, and also I got a jpa/hibernate error.
I hope I made myself clear, and code supplied is enough.
thanks
I was wondering if it's possible with jpa or hibernate, to build a query for retrieving an ApplicationForm entity with a Dictionary for a specific locale, for example 'it' only.
Not with standard JPA. But Hibernate allows to apply arbitrary filters to a collection load during a given session. From the Hibernate Annotations Reference Guide:
2.4.8. Filters
Hibernate has the ability to apply
arbitrary filters on top of your data.
Those filters are applied at runtime
on a given session. First, you need to
define them.
#org.hibernate.annotations.FilterDef
or #FilterDefs define filter
definition(s) used by filter(s) using
the same name. A filter definition has
a name() and an array of
parameters(). A parameter will allow
you to adjust the behavior of the
filter at runtime. Each parameter is
defined by a #ParamDef which has a
name and a type. You can also define a
defaultCondition() parameter for a
given #FilterDef to set the default
condition to use when none are defined
in each individual #Filter. A
#FilterDef(s) can be defined at the
class or package level.
We now need to define the SQL filter
clause applied to either the entity
load or the collection load. #Filter
is used and placed either on the
entity or the collection element
#Entity
#FilterDef(name="minLength", parameters=#ParamDef( name="minLength", type="integer" ) )
#Filters( {
#Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length"),
#Filter(name="minLength", condition=":minLength <= length")
} )
public class Forest { ... }
When the collection use an association
table as a relational representation,
you might want to apply the filter
condition to the association table
itself or to the target entity table.
To apply the constraint on the target
entity, use the regular #Filter
annotation. However, if you wan to
target the association table, use the
#FilterJoinTable annotation.
#OneToMany
#JoinTable
//filter on the target entity table
#Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length")
//filter on the association table
#FilterJoinTable(name="security", condition=":userlevel >= requredLevel")
public Set<Forest> getForests() { ... }
See also
Chapter 17. Filtering data In the Hibernate Core Reference Documentation.
Hibernate3 Filters

Why doesn't the Hibernate generate a DDL with column for serialVersionUID?

I get this DDL (postgres target) when I add the goal hbm2ddl using the Maven plugin hibernate3-maven-plugin:
create table listing (
id varchar(36) not null,
hash_code int4 not null,
version int4,
name varchar(100),
primary key (id)
);
I defined all the columns shown.
All examples of using that I have seen on the web of:
private static final long serialVersionUID = -8402611044513083864L;
never have a #Column annotation. My DDL does not have a column for it. Does anybody else's?
So how does the deserialization code in Java know what version of a class was serialized and stored vs the one that it is being deserialized into?
Serial version UID is used when object is serialized / deserialized.
If you annotate your object as an JPA Entity you're not using a serialization but just transforming your object to another representation - as a row in the database table.
When you fetch the row from the database, this data is used to create a new instance of object with properly set state.
Serialization, on the other hand, is used if you want to construct a binary representation of your object and then recreate the object instance using deserialization process.
Note that you can use serialization with JPA i.e. if you want to persist a field (within your JPA entity) which is neither a basic type, embeddable nor other entity but just a plain Java class which implements Serializable marker interface.
However, in this case only this given field in your entity is using serialization/deserialization to put binary data into database column. Still - the serial version UID is not stored anywhere in the database.
For more information about persistent fields (which are persisted and which are not) you can take a look at 2.2 Persistent Fields and Properties chapter in JPA 2.0 FR specification.
static values are never serialized, and JPA does not use java serialization.

Hibernate / JPA: Map a legacy database Not Null Foreign Key 'Dummy' value as NULL

Using JPA 1.0, Hibernate 3.4*
I have to develop a JPA solution over a legacy system where foreign keys are defined as NOT NULL with a default value of -999999 (dummy value) to indicate an optional association.
Using #NotFound(action = NotFoundAction.IGNORE) from Hibernate Annotations isn't really helping, since it seems to ignore the #BatchSize annotation, hence producing thousand of single queries whenever the dummy value is encountered.
I suppose I could handle this using a Hibernate UserType but this seems quite elaborate for such a scenario, which is not that uncommon ...
Am I missing some obvious trick or default annotation here ?
Thanks
Try #Where(clause="other_id<>-999999") on the association

How to persist java.util.Set through JPA?

I have a field aliases of type java.util.Set in one Entity. This Set doesn't denote any relationship to an Entity.
How can I store this aliases field through JPA?
How this field get stored in database? I think that for the database, this field is a multi-valued attribute.
How can I store this aliases field through JPA?
JPA 1.0 doesn't support collections of basic types so you'll have to either:
Introduce an entity and map it as a #OneToMany ~or~
Get your Set stored in a BLOB (as a Serializable) ~or~
Mark it #Transient and use another getter/setter to store it using a custom string representation (using a seperator) ~or~
Use an extension of your JPA provider supporting collection of basic types (e.g. Hibernate has the #CollectionOfElements annotation).
Solution #1 would be the cleanest portable solution. Solution #2 can lead to some troubles on upgrades. Solution #3 is a ugly workaround for #2. Solution #4 is clean but non portable.
In JPA 2.0, there is the #ElementCollection annotation for this use case (this is of course the ideal solution).
How this field get stored in database
Depending on the chosen implementation, it may be in a BLOB, in a VARCHAR, in another table.

Categories

Resources