Programming experiences
theapplicationbox.com's blog discussing JEE technologies and web related experiences
Tuesday, March 19, 2013
Use "hibernate.hbm2ddl.auto=update" to update your schema (add remove columns, etc.) without losing data in tables.
Use <property name="hibernate.hbm2ddl.auto" value="update" />
to update your schema (add remove columns, etc.) without losing data in tables.
You can now freely add remove fields in your Java entities and on next run of your program, Hibenate will update the tables without droping them (in contrast to "create", see Hibernate docs for possible values)
Wonderful!
Friday, March 8, 2013
Hibernate Compatibility Matrix
If you want to use JPA 1.0 and Hibernate, see
https://community.jboss.org/wiki/HibernateCompatibilityMatrix?_sscc=t
You need for example:
- Hibernate 3.3.2 GA:
hibernate3.jar
+(from lib/bytecode:)
javassist-3.9.0.GA.jar
+(from lib/required)
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
jta-1.1.jar
slf4j-api-1.5.8.jar
and
Hibernate 3.4.0.GA (entity manager)
hibernate-entitymanager.jar
ejb3-persistence.jar
and
Hibernate 3.4.0.GA annotations
hibernate-commons-annotations.jar
hibernate-annotations.jar
For JPA 2 (meaning Hibernate greater than 3.5)
the docs says:
Please note that as of 3.5.x Hibernate Core, Hibernate Annotations and Hibernate EntityManager are all versioned and released together which greatly simplifies this matrix; see this blog for details.
Hibernate Compatibility Matrix
Created on: Apr 23, 2010 3:01 PM by Brad Maxwell - Last Modified: Jul 22, 2012 8:29 PM by Ondrej Zizka
Please note that as of 3.5.x Hibernate Core, Hibernate Annotations and Hibernate EntityManager are all versioned and released together which greatly simplifies this matrix; see this blog for details.
Hibernate Commons Annotations is a utility project used by annotations based sub-projects like Hibernate Search, and thus maintained as a separate project. It is a compile time dependency for Hibernate Core 3.6.0 and up.
| Package | Version | Core | Annotations | EntityManager | Validator | Search | Shards | Tools |
|---|---|---|---|---|---|---|---|---|
Hibernate Core
| 3.2.6 GA | - | 3.2.x, 3.3.x | 3.2.x, 3.3.x | 3.0.x | 3.0.x | 3.0.x | 3.2.x |
| 3.3.2 GA | - | 3.4.x | 3.4.x | 3.1.x | 3.1.x | Not compatible | Not compatible | |
Hibernate
Annotations
| 3.3.1 GA | 3.2.x | - | 3.3.x | 3.0.x | 3.0.x | 3.0.x | 3.2.x |
| 3.4.0 GA | 3.3.x | - | 3.4.x | 3.1.x | 3.1.x | Not compatible | Not compatible | |
Hibernate
EntityManager
| 3.3.2 GA | 3.2.x | 3.3.x | - | 3.0.x | 3.0.x | Not compatible | 3.2.x |
| 3.4.0 GA | 3.3.x | 3.4.x | - | 3.1.x | 3.1.x | Not compatible | Not compatible | |
Hibernate
Validator
| 3.0.0 GA | 3.2.x | 3.3.x | 3.3.x | - | 3.0.x | 3.0.x | 3.2.x |
| 3.1.0 GA | 3.3.x | 3.4.x | 3.4.x | - | 3.1.x | Not compatible | Not compatible | |
Hibernate
Search
| 3.0.1 GA |
>= 3.2.2
(better if >= 3.2.6)
|
3.3.x
(better if >= 3.3.1 )
| 3.3.x | 3.0.x | - | 3.0.x | (3.2.x) |
| 3.1.1 GA | 3.3 | 3.4 | 3.4 | 3.1 | - | Not tested | (3.2.x) | |
Hibernate
Shards
| 3.0 Beta2 | 3.2.x | 3.3.x | Not compatible | 3.0.x | 3.0.x | - | - |
Hibernate
Tools
| 3.2.2 | 3.2.x | 3.2.x and 3.3.x | 3.2.x and 3.3.x | 3.0.x | (3.2.0) | - | - |
Tuesday, March 5, 2013
Co-existence with Hibernate, JPA, and EJB3
Very interesting
1. How to use JPA entities with standard Hibernate Session:
+ use Hibernate's AnnotationConfiguration class or Spring's org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
2. Or how to configure JPA with hibernate.cfg.xml:
See original post:
Co-existence with Hibernate, JPA, and EJB3
http://bill.burkecentral.com/2007/07/06/co-existence-with-hibernate-jpa-and-ejb3/
Also see javadoc for Spring's AnnotationSessionFactoryBean
org.springframework.orm.hibernate3.annotation
1. How to use JPA entities with standard Hibernate Session:
<hibernate-configuration>
<session-factory>
<mapping class="com.acme.Flight"/>
<mapping class="org.jboss.Sky"/>
<mapping resource="org.acme.orm.xml"/>
</session-factory>
</hibernate-configuration>
+ use Hibernate's AnnotationConfiguration class or Spring's org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
2. Or how to configure JPA with hibernate.cfg.xml:
<properties>
<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
</properties>
See original post:
Co-existence with Hibernate, JPA, and EJB3
http://bill.burkecentral.com/2007/07/06/co-existence-with-hibernate-jpa-and-ejb3/
Co-existence with Hibernate, JPA, and EJB3
July 6, 2007
11 Votes
How can you slowly migrate existing Hibernate apps to JPA? How can you use Hibernate features and unique mapping capabilities with a JPA deployment? How can you take advantage of EJB3 injection and persistence context management with Hibernate? In this blog I want to show how Hibernate, JPA, and EJB 3.0 can co-exist and compliment one another. This information is fully documented between the Hibernate and JBoss EJB3 projects, but I thought I’d highlight them in this blog to make the community aware that they exist.
Mixing and matching JPA annotations within Hibernate
Using the standard JPA annotations helps out greatly in cutting down the amount of XML metadata you have to type. This annotation metadata is an exact replacement for much of the metadata in hbm.xml. Using them does not require you to use the JPA EntityManager interface. You may still use SessionFactory and Session objects to interact with your database. After downing the Hibernate Anotations project, setting things up is fairly easy:
SessionFactory sessionFactory =
new AnnotationConfiguration().buildSessionFactory();
You use hibernate.cfg.xml to specify which exact classes you want mapped by this SessionFactory:
<hibernate-configuration> <session-factory> <mapping class="com.acme.Flight"/> <mapping class="org.jboss.Sky"/> <mapping resource="org.acme.orm.xml"/> </session-factory> </hibernate-configuration>
You can mix hbm.xml mapping files with new annotated classes. XML resources can also either be JPA-based XML or Hibernate based. This mixing and matching allows you to quickly prototype new mappings using JPA, but allows these mappings to co-exist with older Hibernate 3 applications.
There are a few more options for configuration. Check out the Hibernate Annotationsdocumentation for more information.
Use Hibernate to configure JPA
If you want to use the JPA Entity Manager API to code a portable application, you may still want to use Hibernate metadata to map your beans. Although the JPA orm mapping is pretty rich, it is still a subset of Hibernate’s functionality. The Hibernate Annotations project provides additional Hibernate-specific annotations to elaborate a persistence mapping where JPA leaves off. If you prefer XML, you can use hbm.xml files to define the mappings for your entity beans. When loading a persistence archive, Hibernate Entity Manager will automatically scan the .jar file for any *hbm.xml files and add them to its mapping information.
Hibernate specific configuration is defined in the properties element of the persistence.xml file. You can configure any hibernate property within this XML blob
<persistence>
<persistence-unit name="manager1" transaction-type="JTA">
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
</persistence-unit>
</persistence>
You may also define all your hibernate configuration in the usual Hibernate way: within a hibernate.xfg.xml file. You must tell the JPA implementation to use this configuration file through the hibernate.ejb.cfgfile property.
<persistence> <persistence-unit name="manager1" transaction-type="JTA"> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/> </properties> </persistence-unit> </persistence>
Also see javadoc for Spring's AnnotationSessionFactoryBean
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html
org.springframework.orm.hibernate3.annotation
Class AnnotationSessionFactoryBean
java.lang.Objectorg.springframework.orm.hibernate3.AbstractSessionFactoryBean
org.springframework.orm.hibernate3.LocalSessionFactoryBean
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
- All Implemented Interfaces:
- BeanClassLoaderAware, DisposableBean, FactoryBean, InitializingBean, ResourceLoaderAware, PersistenceExceptionTranslator
public class AnnotationSessionFactoryBean
- extends LocalSessionFactoryBean
- implements ResourceLoaderAware
Subclass of Spring's standard LocalSessionFactoryBean for Hibernate, supporting JDK 1.5+ annotation metadata for mappings.
Note: This class requires Hibernate 3.2 or higher, with the Java Persistence API and the Hibernate Annotations add-on present.
Example for an AnnotationSessionFactoryBean bean definition:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <value>test.package.Foo</value> <value>test.package.Bar</value> </list> </property> </bean>Or when using classpath scanning for autodetection of entity classes:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="test.package"/> </bean>
Monday, December 17, 2012
In SVN and Eclipse, if you have problems with a folder, with a small red x, try right-click->Team->Revert and then right-click->Team->Refresh/Cleanup
In SVN and Eclipse, if you have problems with a folder, with a small red x, try right-click->Team->Revert and then right-click->Team->Refresh/Cleanup.
Then try to commit again, it should work.
Then try to commit again, it should work.
Friday, November 23, 2012
Using your Locale across requests and ignoring the Faces computed locale
if you want to use your Locale in a faces application, keep it in a session-scoped bean and use it like this
<f:view locale="#{myBean.myLocale}">
<f:loadBundle var="messages" basename="messages.Messages"></f:loadBundle>
You may wonder why not set your Locale (setLocale()) once on the viewHandler.
It is not enough because Faces computes its own locale on every request (or page refresh F5).
So you should do it and every request and this is exactly what <f:view locale="#{myBean.myLocale}"> ensures: that your locale is set as the view's locale on every request (and even if i wanted to set it explicitly on every request using viewHandler.setLocale() i didn't find any right event/timing to do it before the <f:loadBundle is processed. Even the preRenderView event i had learned about is not good)
This will ensure that even if you refresh the page, it is YOUR locale (from the bean propery) and not the Faces-computed locale (the browser locales filtered by <supported-locale>s or the <default-locale> if no <supported-locale> are specified) that will be used.
Friday, July 27, 2012
Primary Keys through OneToOne and ManyToOne Relationships
Primary Keys through OneToOne and ManyToOne Relationships
and this
Derived Identifiers
and this
Derived Identifiers (other source)
and this
Derived Identifiers
and this
Derived Identifiers (other source)
Primary Keys through OneToOne and ManyToOne Relationships
A common model is to have a dependent object share the primary key of its parent. In the case of aOneToOne the child's primary key is the same as the parent, and in the case of a ManyToOne the child's primary key is composed of the parent's primary key and another locally unique field.JPA 1.0 does not allow
@Id on a OneToOne or ManyToOne, but JPA 2.0 does.One of the biggest pitfalls when working with composite primary keys comes with the implementation of associations to entity classes whose tables have multi-column primary keys (using the @JoinColumns annotation). Many JPA implementations may throw seemingly inconsistent exceptions when not specifying referencedColumnName for every @JoinColumn annotation, which JPA requires (even if all referenced column names are equal to the ones in the referencing table). See http://download.oracle.com/javaee/5/api/javax/persistence/JoinColumns.html
[edit] JPA 1.0
Unfortunately JPA 1.0 does not handle this model well, and things become complicated, so to make your life a little easier you may consider defining a generated unique id for the child. JPA 1.0 requires that all@Id mappings be Basic mappings, so if your Id comes from a foreign key column through a OneToOne or ManyToOne mapping, you must also define a Basic @Id mapping for the foreign key column. The reason for this is in part that the Id must be a simple object for identity and caching purposes, and for use in the IdClass or the EntityManager find() API.Because you now have two mappings for the same foreign key column you must define which one will be written to the database (it must be the
Basic one), so the OneToOne or ManyToOne foreign key must be defined to be read-only. This is done through setting the JoinColumn attributes insertable and updatable to false, or by using the @PrimaryKeyJoinColumn instead of the @JoinColumn.A side effect of having two mappings for the same column is that you now have to keep the two in synch. This is typically done through having the set method for the
OneToOne attribute also set the Basic attribute value to the target object's id. This can become very complicated if the target object's primary key is a GeneratedValue, in this case you must ensure that the target object's id has been assigned before relating the two objects.Some times I think that JPA primary keys would be much simpler if they were just defined on the entity using a collection of
Columns
instead of mixing them up with the attribute mapping. This would leave
you free to map the primary key field in any manner you desired. A
generic List could be used to pass the primary key to find()
methods, and it would be the JPA provider's responsibility for hashing
and comparing the primary key correctly instead of the user's IdClass. But perhaps for simple singleton primary key models the JPA model is more straight forward.- TopLink / EclipseLink : Allow the primary key to be specified as a list of columns instead of using
Idmappings. This allowsOneToOneandManyToOnemapping foreign keys to be used as the primary key without requiring a duplicate mapping. It also allows the primary key to be defined through any other mapping type. This is set through using aDescriptorCustomizerand theClassDescriptoraddPrimaryKeyFieldNameAPI.
- Hibernate / Open JPA / EclipseLink (as of 1.2): Allows the
@Idannotation to be used on aOneToOneorManyToOnemapping.
[edit] Example OneToOne id annotation
... @Entity public class Address { @Id @Column(name="OWNER_ID") private long ownerId; @OneToOne @PrimaryKeyJoinColumn(name="OWNER_ID", referencedColumnName="EMP_ID") private Employee owner; ... public void setOwner(Employee owner) { this.owner = owner; this.ownerId = owner.getId(); } ... }
[edit] Example OneToOne id XML
<entity name="Address" class="org.acme.Address" access="FIELD"> <attributes> <id name="ownerId"> <column name="OWNER_ID"/> </id> <one-to-one name="owner"> <primary-key-join-column name="OWNER_ID" referencedColumnName="EMP_ID"/> </one-to-one> </attributes> <entity/>
[edit] Example ManyToOne id annotation
... @Entity @IdClass(PhonePK.class) public class Phone { @Id @Column(name="OWNER_ID") private long ownerId; @Id private String type; @ManyToOne @PrimaryKeyJoinColumn(name="OWNER_ID", referencedColumnName="EMP_ID") private Employee owner; ... public void setOwner(Employee owner) { this.owner = owner; this.ownerId = owner.getId(); } ... }
[edit] Example ManyToOne id XML
<entity name="Address" class="org.acme.Address" access="FIELD"> <id-class class="org.acme.PhonePK"/> <attributes> <id name="ownerId"> <column name="OWNER_ID"/> </id> <id name="type"/> <many-to-one name="owner"> <primary-key-join-column name="OWNER_ID" referencedColumnName="EMP_ID"/> </many-to-one> </attributes> <entity/>
[edit] JPA 2.0
Defining anId for a OneToOne or ManyToOne in JPA 2.0 is much simpler. The @Id annotation or id XML attribute can be added to a OneToOne or ManyToOne mapping. The Id used for the object will be derived from the target object's Id. If the Id is a single value, then the source object's Id is the same as the target object's Id. If it is a composite Id, then the IdClass will contain the Basic Id attributes, and the target object's Id as the relationship value. If the target object also has a composite Id, then the source object's IdClass will contain the target object's IdClass.[edit] Example JPA 2.0 ManyToOne id annotation
... @Entity @IdClass(PhonePK.class) public class Phone { @Id private String type; @ManyToOne @Id @JoinColumn(name="OWNER_ID", referencedColumnName="EMP_ID") private Employee owner; ... }
[edit] Example JPA 2.0 ManyToOne id XML
<entity name="Address" class="org.acme.Address" access="FIELD"> <id-class class="org.acme.PhonePK"/> <attributes> <id name="type"/> <many-to-one name="owner" id="true"> <join-column name="OWNER_ID" referencedColumnName="EMP_ID"/> </many-to-one> </attributes> <entity/>
[edit] Example JPA 2.0 id class
... public class PhonePK { private String type; private long owner; public PhonePK() {} public PhonePK(String type, long owner) { this.type = type; this.owner = owner; } public boolean equals(Object object) { if (object instanceof PhonePK) { PhonePK pk = (PhonePK)object; return type.equals(pk.type) && owner == pk.owner; } else { return false; } } public int hashCode() { return type.hashCode() + owner; } }
Synthax for using a named parameter of type List in JPA Query Language when using Hibenate
example:
WHERE person IN (:persons)
note the (: persons ) notation.
and then you set the paramater as usual:
query.setParamater("persons", myListofPersons);
WHERE person IN (:persons)
note the (: persons ) notation.
and then you set the paramater as usual:
query.setParamater("persons", myListofPersons);
Monday, June 25, 2012
Modify the version of your webapp to 2.5 in a "maven-archetype-webapp" generated web application
By default, maven will generate a version=2.3 and "DTD-style" web.xml.
Also, the "Dynamic Web Module" Facet is set to 2.3. (right-click, see Project Facets)
These 2 configutations are old, you most probably are using Java EE 5 or 6 features and this will surely create you problems when deploying your project on an application server.
For example your @PersistenUnit in your Servlets will not be considered by the application server and those fields will be left null.
Also even the Eclipse will generate problems when deploying to the server.
So, today this this can create problems, as in most cases your apps are modern.
Update your web.xml with this:
<?xml version="1.0" encoding="UTF-8"?> <web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5" > ... </web-app>
Also, update the "Dynamic Web Module" Facet to 2.5. For Eclipse it is not enogh to just change the version in web.xml
Watch this for how to change it to 2.5, i recopy the steps here:
1. Uncheck the Dynamic Web Module facet checkbox and click Apply.
2. Re-check the Dynamic Web Module facet, choose version 2.5 (or 3.0) and click “Further Configuration”.
3. In the Content Directory field, type “/src/main/webapp”. Be sure that the “Generate web.xml deployment descriptor” is checked. Click OK.
4. Click Apply, then click OK.
In Eclipse Maven can't download an artifact: use the checkbox"Force Update of snapshots/releases"
Right click your project, Maven->Update Dependencies than tick the "Force Update of snapshots/releases", then OK.
Subscribe to:
Posts (Atom)
Use "hibernate.hbm2ddl.auto=update" to update your schema (add remove columns, etc.) without losing data in tables.
Use <property name="hibernate.hbm2ddl.auto" value="update" /> to update your schema (add remove columns, etc...
-
In SVN and Eclipse, if you have problems with a folder, with a small red x, try right-click->Team->Revert and then right-click->Te...
-
Use <property name="hibernate.hbm2ddl.auto" value="update" /> to update your schema (add remove columns, etc...
-
Read this: Primary Keys through OneToOne and ManyToOne Relationships and this Derived Identifiers and this Derived Identi...
