- This topic has 7 replies, 3 voices, and was last updated 16 years, 9 months ago by
tsomerville.
-
AuthorPosts
-
Steve PriorMemberI know that Hibernate 3.2 function supports the JPA way of doing things, but isn’t it backward compatable with “Add Hibernate Capabilities” as well? When I create a Java project and “Add Hibernate Capabilities” there is no option to use the Hibernate 3.2 libraries. I would think it would be listed there as well as in “Add JPA capabilities”.
Steve PriorMemberI should have mentioned that this was related to MyEclipse 5.5 M2.
Riyad KallaMemberHibernate 3.2 will be added in MyEclipse 5.5, and it is listed in the Add JPA Capabilities wizard:
Attachments:
You must be logged in to view attached files.
Steve PriorMemberYeah, but that’s not what I asked at all. I’m using HIbernate 5.5M2 and saw it listed in the “Add JPA capabilities” wizard, but shouldn’t the Hibernate 3.2 libraries also be listed as an option when using the “Add hibernate capabilities” wizard? It seems to me that the two different wizards are different approaches to setting up similar capabilities and Hibernate 3.2 fits into both of them.
Riyad KallaMemberDoh, sorry I was on auto-pilot this morning.
The Hibernate capabilities follow the same generation routine they have in prior releases, by generating a Hibernate.cfg.xml file and subsequent hbm.xml mapping files for each entity.
The “JPA method” of generating entities that are annotated with the JPA annotations is the newer method of generation following the JEE 5 specification.
And yes you are right, Hibernate 3.2 fits into both of them, we just haven’t added Hibernate 3.2 to the library list for the “original hibernate way” yet.
Steve PriorMemberGood, thanks. I just wanted to mention it now so it might be fixed for the GA release.
Steve PriorMemberHibernate 3.2 still isn’t listed in MyEclipse 6.0M1 when “adding hibernate capabilities” to a project. Come on guys, this is an easy one 🙂
tsomervilleMemberHere’s my best workaround for getting to have the best of JPA and a Hibernate session factory.
There might be easier ways to do this, but I just wanted to share what I’ve come up with in MyEclipse.I was using a JPA enabled project, and I wanted to see the exported schema generation that Hibernate offers. Plus, there were some examples in my book that I wanted to follow along with better, but couldn’t get to work in the MyEclipse JPA project.
Please let me know if there is a simpler way, or if this helped anyone.
If you want a nicely formatted version with follow-along pictures, contact me with obvious subject line (the tutorial below looks sub-optimal).
-Travis Somerville
travis_somerville2000 at yahoo.comCreating a JPA Enabled Project with Hibernate 3.2 annotations:
Create a plain Java project.
MyEclipse, right click project node and add JPA Capabilities.
Choose hiberate persistent jars.Make a new database connection if needed.
Create a persistence unit with that database connection.
Check “enable dynamic” table creation if you are in a development mode.Don’t forget to make a new package to hold your JPA objects.
Reverse engineering the Database:
In DB Browser, select all the tables, right click, and choose JPA Reverse Engineering.
This brings up the dialog to choose what you want to create.OR, if that wizard can’t see your JPA project, right click the project in Package Explorer and “Generate Entities and DAO’s”.
If you take this path, you need to add what database tables you are interested in, like so:Create the entities and the DAO’s, for the most functionality.
Don’t forget to “Browse” for the correct Java package — this is the only way it knows where to put the Entity objects.Adding Annotated Hibernate Session to your JPA project:
Create a java project, add hibernate 3.1 capablilities.
Copy the HibernateSessionFactory.java object over, and modify any instances of Configuration to be an AnnotationConfiguration object.
private static AnnotationConfiguration configuration = new AnnotationConfiguration();Go generate the Hibernate ways of DAO in the hibernate project, and copy over those DAO’s to your JPA project.
Copy over the BaseHibernateDAO and IBaseHibernateDAO java files as well.
Add an import into each Hibernate DAO to see the JPA annotated classes.Note, the visual editor that adds a java “resource” will not work for the 3.2 Hibernate annotations. Instead, add the annotated class to the hibernate.cfg.xml with this style:
<mapping class=”openlending.jpa.Claims” />Another way is to edit the HibernateSessionFactory.java object to addAnnotatedClass like so:
configuration.configure(configFile); configuration.addAnnotatedClass(openlending.jpa.Claims.class); sessionFactory = configuration.buildSessionFactory();Notice how we didn’t add a string, we added a class.
Now you have 3.2 Hibernate libraries with JPA as well. This allows you to use the Hibernate way of getting a session and using these JPA objects.
This allows you to add Hibernate Shards, or just follow along in the Hibernate tutuorials better. This also allows you to add Hibernate xml configuration overrides in addition to JPA when you don’t know or there does not exist an annotation.
Here is a picture of my project file structure:
Example Test case:
Here’s an example of my Test class that calls both types:
import java.util.List; import openlending.jpa.*; import hibernate.*; public class Test { public static void main(String[] args) { System.out.println("Testing JPA way."); openlending.jpa.ClaimsDAO claimsJPA = new openlending.jpa.ClaimsDAO(); List<openlending.jpa.Claims> claims = claimsJPA.findAll(); if (claims == null) System.out.println("No claims."); else System.out.println("Number of JPA claims "+ claims.size()); System.out.println("Testing Hibernate way."); hibernate.ClaimsDAO claimsHIB = new hibernate.ClaimsDAO(); List<openlending.jpa.Claims> claims2 = claimsHIB.findAll(); if (claims2 == null) System.out.println("No claims."); else System.out.println("Number of HIB claims "+ claims2.size()); } } Example hibernate.cfg.xml: <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">xxxx</property> <property name="connection.url"> jdbc:mysql://database_name:3306/your_db_instance </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="myeclipse.connection.profile"> dev travis1 </property> <property name="hbm2ddl.auto">update</property> <property name="connection.password">xxxxx</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <mapping resource="hibernate/Claims.hbm.xml" /> </session-factory> </hibernate-configuration> Example persistence.xml: <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="JPAMapOpenLending1PU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>openlending.jpa.DebtIncomeLog</class> ... ... <class>openlending.jpa.ApplicantId</class> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://database_name:3306/your_db_instance" /> <property name="hibernate.connection.username" value="xxxx" /> <property name="hibernate.connection.password" value="xxxxxxxx" /> <property name="hibernate.hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence> Example HibernateSessionFactory.java: package hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static AnnotationConfiguration configuration = new AnnotationConfiguration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); configuration.addAnnotatedClass(openlending.jpa.Claims.class); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } } Example Hibernate DAO: package hibernate; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example; import openlending.jpa.*; /** * A data access object (DAO) providing persistence and search support for * Claims entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see hibernate.Claims * @author MyEclipse Persistence Tools */ public class ClaimsDAO extends BaseHibernateDAO { private static final Log log = LogFactory.getLog(ClaimsDAO.class); public void save(Claims transientInstance) { log.debug("saving Claims instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Claims persistentInstance) { log.debug("deleting Claims instance"); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Claims findById(java.lang.Integer id) { log.debug("getting Claims instance with id: " + id); try { Claims instance = (Claims) getSession().get("hibernate.Claims", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Claims instance) { log.debug("finding Claims instance by example"); try { List results = getSession().createCriteria("hibernate.Claims").add( Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Claims instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Claims as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findAll() { log.debug("finding all Claims instances"); try { String queryString = "from Claims"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Claims merge(Claims detachedInstance) { log.debug("merging Claims instance"); try { Claims result = (Claims) getSession().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Claims instance) { log.debug("attaching dirty Claims instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Claims instance) { log.debug("attaching clean Claims instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } } Example JPA annotated class: package openlending.jpa; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Claims entity. * * @author MyEclipse Persistence Tools */ @Entity @Table(name = "claims", catalog = "travis1", uniqueConstraints = {}) public class Claims implements java.io.Serializable { // Fields private Integer yourId; private String adjusterUsername; private Date dateTimeClaimProcessed; private String contactFName; ... ... // Property accessors @Id @Column(name = "yourID", unique = true, nullable = false, insertable = true, updatable = true) public Integer getYourId() { return this.yourId; } public void setYourId(Integer yourId) { this.yourId = yourId; } @Column(name = "adjusterUsername", unique = false, nullable = false, insertable = true, updatable = true, length = 50) public String getAdjusterUsername() { return this.adjusterUsername; } ... ...
-
AuthorPosts