JPA using variable Schema name in annotations - java

I'm using the Java Persistence API to describe tables from my database that i will manipulate in my code.
However, the schema used is not be the same depending on where my project will be installed. So, when I use the annotations, I would like that the SCHEMA field was a variable, but I can't make it:
#Entity
#Table(name = "TABLE_NAME", schema = schemaVariable, catalog = "")
How can I achieve that?
Is it possible with the persistence.xml file?

No, this is not possible. You can only use compile-time constants (which are all primitives and String) in annotations.
You can use final variables:
public class DatabaseMetadata {
public static final SCHEMA = "MySchema";
}
and then use it in annotation:
#Table(name = "TABLE_NAME", schema = DatabaseMetadata.SCHEMA, catalog = "")
but I think it's not what you wanted.
PS. On the other hand, there can be find examples of using i.e. Spring EL in annotations (see #Value annotation), but this requires custom annotation processor. AFAIK none of JPA providers gives you such ablility.

Putting schema information (like table, column, schema names) in java classes is a bad idea any time IMHO (forcing recompile if you want to deploy elsewhere). You could put that info in orm.xml and just deploy a different orm.xml dependent on your deployment requirement.
As for persistence.xml you would be dependent on your JPA provider having a persistence property that defined the default schema/catalog. I know DataNucleus JPA (what I use) has this, but no idea for Hibernate

If you know that you would be using different schemas, I'd suggest to use 2 mapping files and define
<entity-mappings>
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>HR</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
...
</entity-mappings>
In this way you will be able to easily change schemas, without any changes in the application code.

Related

How to dynamically add Entity in Hibernate?

I'm a java developer. I'm using spring 4.0.1 and hibernate 4.2.21. I have a class as follow:
#Entity
#Inheritance(...)
public abstract class Feature{
#Id
#GeneratedValue
protected Long id;
...
}
Now I have some many class as follow:
Label.java class:
#Entity
public class Label extends Feature{
protected String str;
...
}
Point.java class:
#Entity
public class Point extends Feature{
protected Integer intg;
...
}
I have more than 20 Entity class that extends from Feature class. Is there any way to add dynamically this classes(such as Label and Point) to the project without writing hard code?
update:
For example, Hibernate get data from a database and then according this data, create models.
Is it possible?
How do I do?
I think its not a good database design that needs to be changed dynamically. It sounds verbose and not consistent. Observe your domain again and try to design a proper entity relationships that wouldnt be changed over run time.
You can try to collect the needed data to build the model and generate a hibernate hbm.xml file for each entity (is xml format and easy to generate with java after reading the data needed as you describe in your update)
After that, you can create programmatically a hibernate configuration object following this http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html#configuration-programmatic
I Think with that approach you can achieve what you want if I understand well your question.
I think you want to generate your entity class at runtime instead of that you have to write your java file and compile it and so on.
If this is your requirement you can use a byte code generator like javassist to generate and annotate your class file at runtime. Then you can persist it to your table using JPA, Hibernate and any other ORM framework.
As I understand you need to develop a tool, collects table names that have one-to-one relationship with Feature table.
My suggestion is like that (tested with Oracle):
1) From your DB, get tables metadata who is referancing your Feature table.
Below will print your Label, Point, etc tables who has foreign key relation to your table.If you want to only generate a subset (irrelevant tables might has this relationship too) may be you put a common foreign key column name and filter out non-related tables with a help of such marking.
Connection connection = jdbcTemplate.getDataSource().getConnection();
DatabaseMetaData metaData = connection.getMetaData();
ResultSet exportedKeys = metaData.getExportedKeys(connection.getCatalog(), "<your_schema_name>", "FEATURE");
while (exportedKeys.next()){
String fkTableName = exportedKeys.getString("FKTABLE_NAME");
String fkColumnName = exportedKeys.getString("FKCOLUMN_NAME");
System.out.println("[fkTableName:" + fkTableName + "], [fkColumnName" + fkColumnName + "]");
}
exportedKeys.close();
2) For the tables you collected above, for each table of our concern, get table metadata for the types and columns.
ResultSet columns = metaData.getColumns(connection.getCatalog(), "<your_schema_name>", "<your_table_name>", null);
while (columns.next()){
String columnName = columns.getString("COLUMN_NAME");
String typeName = columns.getString("TYPE_NAME");
System.out.println("[columnName:" + columnName + "], [typeName" + typeName + "]");
}
columns.close();
3) According to result from 2 generate your Java classes. With fields, getter setters, annotations etc. Then copy them into your source directory. You know the rest :)
Hope this is helpful.
I think you can use Hibernate Reverse Engineering to generate Entity for all the database tables. Please refer this Link. That will explained step by step process to generate entity from database using hibernate reverse engineering.
Do not repeat yourself.
If you really need those classes use an IDE (like eclipse) to generate the classes. Or use generics and inheritance to create only one class that is capable of storing Strings as well as Integers.
But if you do not actually need classes, generate SQL (not JPQL nor HQL) and to store the data in java.util.Map and similar data structures.
Classes are good for:
type safety
combining logic (methods) with data (fields)
describing relationships
In your case you might only need:
store structured data at runtime.
I think you could do this with eclipse, but the classes had to be modified more or less to preserve the inheritance hierarchy.
Righ click on the project name and select Properties
Use project facets if project facets not enabled
Click the JPA if it's not selected, then click OK to close the project properties window.
After enabling JPA in project properties, now right click you eclipse project name again, you should see a new context menu item JPA tools appears. Choose Generate Entities from tables
Select a database connection to let Eclipse get the tables used to generated
class from.
Here is how to setup db in eclipse
It's better to create the entities in a dummy project using the above method and copy the Entity classes to the real project.
Eclipse's Class refactoring may be used to preserve the inheritance hierarchy that you want.
Hope this helps.

How to overwrite JPA entity's #Table.catalog value?

When I use IntelliJ to generate a persistence mapping from exisitng database schema it puts a catalog value as part of #Table annotation. Unfortunately names of database instances have names of dev/test/prod environemnts in them and while I can overwrite the connection string with a map passed to EntityManagerFactory I still get Invalid object name 'BAR_DEV.dbo.FOO' when executing a query against BAR_TEST instance.
Can I dynamically overwrite the catalog value at runtime without doing global search and replace to remove it manually after entity generation?
#Entity
#Table(name = "FOO", schema = "dbo", catalog = "BAR_DEV")
public class Foo{ /* ... */ }
No, it is not possible directly with standard JPA.
However, a solution I used in my project was to define multiple persistence units, each for a particular environment. You may overwrite any database mapping in an orm.xml file, or even set default catalog or schema for all entities. Next step is to dynamically retrieve proper EntityManager - if you are using Java EE, I recomment injecting using #Inject and creating a producer, which returns particular EM for specified environment.
Non portable, Eclipselink only org.eclipse.persistence.dynamic.DynamicHelper.SessionCustomizer can replace many defaults at runtime.
EDIT: I haven't ready code for You. I use this way
public void customize(Session session) throws SQLException {
...
for (ClassDescriptor descriptor : session.getDescriptors().values()) {
if (!descriptor.getTables().isEmpty() && descriptor.getAlias().equalsIgnoreCase(descriptor.getTableName())) {
tableName = TABLE_PREFIX + clazz.getSimpleName();
descriptor.setTableName(tableName);
}
}

How to override an annotation-defined table name in JPA?

I have tables that have this annotation structure in my application and I use JpaRepository for CRUD operations.
#Entity
#Table(name = "FOO")
public class Foo implements Serializable {
…
}
But I need to override only the table name (not any of the #Column etc. attributes) from an orm.xml or properties file without changing the actual code. I've searched and I couldn't find a way to do it in Spring Data JPA. Am I missing something here or it is not supported?
Firstly, Spring Data is not a JPA provider but simply a 'helper' library providing a wrapper round common persistence operations. The JPA specification however does provide a mechanism for overriding annotations via an XML mapping file. So assuming your provider (Hibernate, EclipseLink, OpenJPA or whatever) fully implements the JPA specification then you should be able to do this.
However it would appear that you cannot override only the table name: unless your column names are mapped to the default values then, as far as I can see, you need to specify each column in the mapping file - which is slightly inconvenient I suppose.
The book Pro JPA 2 : Mastering the Java Persistence API notes:
The metadata-complete attribute is an attribute on the entity,
mapped-superclass, and embeddable elements. If specified, all
annotations on the specified class and on any fields or properties in
the class will be ignored, and only the metadata in the mapping file
will be considered as the set of metadata for the class. When
metadata-complete is enabled, the same rules that we applied to
annotated entities will still apply when using XML-mapped entities.
For example, the identifier must be mapped, and all relationships must
be specified with their corresponding cardinality mappings inside the
entity element.
So you will need an entry in your orm.xml like the below, adding other attributes as required.
<entity-mappings>
<entity class="examples.Foo" metadata-complete="true">
<table name="NEW_FOO"/>
<attributes>
<id name="id"/>
</attributes>
</entity>
</entity-mappings>

Hibernate reveng persistence model does not validate

I use Hibernate Reverse Engineering to automatically create classes from a database scheme. DB server is MSSQL 2008. This database is designed by a partner and could potentially change without notice. Thus I'd like to have Hibernate validate the scheme on startup, wich in my opinion should work out of the box. But it doesn't:
org.hibernate.HibernateException: Wrong column type in somedb.dbo.ASVC_S for column SomeCol. Found: decimal, expected: numeric(18,0)
The generated enttity class looks like this:
#Column(name="SomeCol", precision=18)
public BigDecimal getSomeCol() {
return this.someCol;
}
Is my assumption that reveng creates classes that can be validated against the schema wrong? Should I skip validation and hope that during runtime everything's OK? Annotating the classes after generating them or maintaining an entry for each class in my reveng.xml mapping file is not an option - too many classes ;)
hibernate-tools is version 4.0.0-CR1.

Is is possible to create a custom jpa annotation in java

Jpa one of the big successfull module of jpa and so are its annotation features .I have weird requirement in which i need to create jpa annotation ,one that jpa can process
ex. We have in jpa a table annotation that create a table for this java pojo class.
i need to make another annotation that behaves exactly as what table annotation does + some of my custom reqirements;
what is mean
if i create a customAnnotation like #Anil that is suppose to work same as #Table Annotation does
than
#Anil
public class Anp
{
}
than this should create a table in the database is that possible or not .if it is give me some way to do this
thanks
JPA does not process just any annotation. The JPA implementation processes the annotations that it supports and these are typically just the javax.persistence annotations, and optionally its own extensions. Your JPA provider may allow you to define your own, but this is not going to be very common - look at the docs for your JPA provider if they allow a user to define annotations.
For example, the JPA provider I have used (DataNucleus JPA) allows the user to provide annotations for the class or for the field/property.

Categories

Resources