Results 1 to 18 of 18
Like Tree3Likes
  • 1 Post By r035198x
  • 1 Post By r035198x
  • 1 Post By r035198x

Thread: JSF + Hibernate

  1. #1
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default [SOLVED] JSF + Hibernate

    Hi all,

    I'm having a problem with integrating Hibernate with a J2EE Web App. I have the file hibernate.cfg.xml with all Class mappings, but when I run my application Hibernate doesn't start. Do I need to configure something else to integrate Hibernate with JSF, am I missing something?

    pom.xml
    Java Code:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>dev.playground</groupId>
    	<artifactId>JSF-PrimeFaces-SimpleLogin</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>war</packaging>
    
    	<name>JSF-PrimeFaces-SimpleLogin</name>
    
    	<properties>
    		<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    	</properties>
    
    	<repositories>
    		<repository>
    			<id>prime-repo</id>
    			<name>Prime Technology Maven Repository</name>
    			<url>http://repository.prime.com.tr</url>
    			<layout>default</layout>
    		</repository>
    	</repositories>
    	
    	<dependencies>
    		<dependency>
    			<groupId>javax</groupId>
    			<artifactId>javaee-web-api</artifactId>
    			<version>6.0</version>
    			<scope>provided</scope>
    		</dependency>
    
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.8.2</version>
    			<scope>test</scope>
    		</dependency>
    		
    		<dependency>
    			<groupId>org.primefaces</groupId>
    			<artifactId>primefaces</artifactId>
    			<version>2.2.1</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.primefaces.themes</groupId>
    			<artifactId>casablanca</artifactId>
    			<version>1.0.1</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.primefaces.themes</groupId>
    			<artifactId>aristo</artifactId>
    			<version>1.0.1</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.hibernate</groupId>
    			<artifactId>hibernate-core</artifactId>
    			<version>3.6.5.Final</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-log4j13</artifactId>
    			<version>1.0.1</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>5.1.17</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>javassist</groupId>
    			<artifactId>javassist</artifactId>
    			<version>3.12.1.GA</version>
    			<type>jar</type>
    			<scope>compile</scope>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>2.3.2</version>
    				<configuration>
    					<source>1.6</source>
    					<target>1.6</target>
    					<compilerArguments>
    						<endorseddirs>${endorsed.dir}</endorseddirs>
    					</compilerArguments>
    				</configuration>
    			</plugin>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-war-plugin</artifactId>
    				<version>2.1.1</version>
    				<configuration>
    					<failOnMissingWebXml>false</failOnMissingWebXml>
    				</configuration>
    			</plugin>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-dependency-plugin</artifactId>
    				<version>2.1</version>
    				<executions>
    					<execution>
    						<phase>validate</phase>
    						<goals>
    							<goal>copy</goal>
    						</goals>
    						<configuration>
    							<outputDirectory>${endorsed.dir}</outputDirectory>
    							<silent>true</silent>
    							<artifactItems>
    								<artifactItem>
    									<groupId>javax</groupId>
    									<artifactId>javaee-endorsed-api</artifactId>
    									<version>6.0</version>
    									<type>jar</type>
    								</artifactItem>
    							</artifactItems>
    						</configuration>
    					</execution>
    				</executions>
    			</plugin>
    		</plugins>
    	</build>
    
    </project>
    and hibernate.cfg.xml

    Java Code:
    <?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">
    <hibernate-configuration>
     <session-factory name="SESSION_FACTORY">
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.password">dev_environment</property>
      <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.format_sql">true</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <property name="hibernate.c3p0.max_size">10</property>
      <property name="hibernate.c3p0.min_size">1</property>
      <property name="hibernate.c3p0.timeout">180</property>
      <property name="hibernate.c3p0.idle_test_period">100</property>
      <property name="hibernate.cache.use_second_level_cache">true</property>
      <property name="hibernate.cache.use_query_cache">true</property>
      <property name="hibernate.c3p0.acquire_increment">1</property>
      <property name="hibernate.c3p0.max_statements">30</property>
      <mapping class="login.UserPOJO"/>
      <mapping class="login.CompanyPOJO"/>
     </session-factory>
    </hibernate-configuration>
    I'm using Maven, so I created a Source folder src/main/config where my hibernate.cfg.xml resides.
    EDIT: I use Eclipse and JBoss 6

    Thank you for reading
    Last edited by buyapentiumjerk; 07-11-2011 at 02:39 PM. Reason: Solved
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  2. #2
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    Ok, I got it working... for the ones interested check this tutorial out: Java EE 6 example application on JBoss 6

    basically:

    1. under [JBOSS_HOME]\server\default\deploy\ create mysql-ds.xml (for MySQL DB):
    Java Code:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <!-- See http://www.jboss.org/community/wiki/Multiple1PC for information about local-tx-datasource -->
    <!-- $Id: mysql-ds.xml 97536 2009-12-08 14:05:07Z jesper.pedersen $ -->
    <!--  Datasource config for MySQL using 3.0.9 available from:
    http://www.mysql.com/downloads/api-jdbc-stable.html
    -->
    
    <datasources>
      <local-tx-datasource>
        <jndi-name>MySqlDS</jndi-name>
        <connection-url>jdbc:mysql://127.0.0.1:3306/test</connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name>root</user-name>
        <password>dev_environment</password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
        <!-- should only be used on drivers after 3.22.1 with "ping" support
        <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
        -->
        <!-- sql to call when connection is created
        <new-connection-sql>some arbitrary sql</new-connection-sql>
          -->
        <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
        <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
          -->
    
        <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
        <metadata>
           <type-mapping>mySQL</type-mapping>
        </metadata>
      </local-tx-datasource>
    </datasources>
    2. Copy mysql-connector-java-X.X.X.jar file to [JBOSS_HOME]\server\default\lib\

    3. Under Project -> Properties -> Project Facets -> Java Server Faces create a new User Library JSF2, and add jboss-faces.jar, jsf-apiX.X.X.jar and jsf-implX.X.X.jar files ([JBOSS_HOME]\server\default\deployers\jsf.deployer\<select your implementation ex:Mojarra-2.0>) and select it (I think that under Project -> Properties -> Project Facets -> Runtimes you can just select JBoss6.0 Runtime but all jar files get copied)

    4. Create persistence.xml file under WEB-INF:
    Java Code:
    <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_2_0.xsd"
    	version="2.0">
    	<persistence-unit name="ejb3-persistence-unit"
    		transaction-type="JTA">
    		<provider>org.hibernate.ejb.HibernatePersistence</provider>
    		<jta-data-source>java:/MySqlDS</jta-data-source>
    		<class>login.UserPOJO</class>
    		<class>login.CompanyPOJO</class>
    		<properties>
    			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
    			<property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/test" />
    			<property name="hibernate.connection.username" value="root" />
    			<property name="hibernate.connection.password" value="dev_environment" />
    			<!-- JDBC connection pool (use the built-in) -->
    			<property name="hibernate.connection.pool_size" value="1" />
    			<!-- SQL dialect -->
    			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
    			<!-- Enable Hibernate's automatic session context management -->
    			<property name="hibernate.current_session_context_class"
    				value="thread" />
    			<!-- Disable the second-level cache -->
    			<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
    			<!-- Echo all executed SQL to stdout -->
    			<property name="hibernate.use_sql_comments" value="true" />
    			<property name="hibernate.show_sql" value="true" />
    			<!-- validate the database schema on startup -->
    			<property name="hibernate.transaction.auto_close_session"
    				value="true" />
    			<property name="hibernate.hbm2ddl.auto" value="update" />
    		</properties>
    	</persistence-unit>
    </persistence>
    As a side note I think it's possible to user hibernate.cfg.xml (it must be), but I just can't seem to be able to use it.

    Tank you
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  3. #3
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Remove all the "hibernate.connection.xxx from your persistence.xml, you already have them in your -ds.xml.
    Declaring them there only allows you to change them without recompiling your code.
    Also, hibernate-core,slf4j and javassist are already provided by JBOSS so declare them as provided. Making them compile duplicates the jars on the classpath opening you to undefined behavior. You should also declare mysql as provided since you have copied it to your server's lib.

    If you still want to use the .cfg.xml file then put it under src/main/resources
    buyapentiumjerk likes this.

  4. #4
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    Hi r035198x,

    thank you for your feedback. I was aiming at using just hibernate.cfg.xml but I'm failing at that. Could you please take a look at my new hibernate.xfg.xml and point me in the right direction?

    hibernate.cfg.xml:
    Java Code:
    <?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">
    <hibernate-configuration>
     <session-factory name="">
      <property name="hibernate.connection.datasource">java:/comp/env/jdbc/MySqlDS</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransaction</property>
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.use_sql_comments">true</property>
      <property name="hibernate.format_sql">true</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <mapping class="login.CompanyPOJO"/>
      <mapping class="login.UserPOJO"/>
     </session-factory>
    </hibernate-configuration>
    mysql-ms.xml
    Java Code:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <!-- See http://www.jboss.org/community/wiki/Multiple1PC for information about local-tx-datasource -->
    <!-- $Id: mysql-ds.xml 97536 2009-12-08 14:05:07Z jesper.pedersen $ -->
    <!--  Datasource config for MySQL using 3.0.9 available from:
    http://www.mysql.com/downloads/api-jdbc-stable.html
    -->
    
    <datasources>
      <local-tx-datasource>
        <jndi-name>MySqlDS</jndi-name>
        <connection-url>jdbc:mysql://localhost:3306/test</connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name>root</user-name>
        <password>dev_environment</password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
        <!-- should only be used on drivers after 3.22.1 with "ping" support
        <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
        -->
        <!-- sql to call when connection is created
        <new-connection-sql>some arbitrary sql</new-connection-sql>
          -->
        <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
        <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
          -->
    
        <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
        <metadata>
           <type-mapping>mySQL</type-mapping>
        </metadata>
      </local-tx-datasource>
    </datasources>
    Eclipse output:
    Java Code:
    11:37:49,250 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=MySqlDS' to JNDI name 'java:MySqlDS'
    I'm using Maven and i was using a Source Folder /src/main/config for hibernate.cfg.xml and log4j.properties but now I'm using src/main/resources. The problem is that Hibernate doesn't startup, does it have anything to do with <property name="hibernate.connection.datasource">java:/comp/env/jdbc/MySqlDS</property>?

    Thank you for your feedback
    Last edited by buyapentiumjerk; 07-11-2011 at 12:44 PM. Reason: Extra info
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  5. #5
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    If the cfg.xml file is not being picked up at all then the problem is its location rather than its contents.
    Where is this file now and how are you running your application?

  6. #6
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    Hi r035198x,

    I'm using Maven and i was using a Source Folder /src/main/config for hibernate.cfg.xml and log4j.properties but now I'm using src/main/resources as you indicated on your last post. I start my application through Eclipse in Debug mode. When I run my app I go to its URL and my Faces page shows up but Hibernate doesn't startup, if I use persistence.xml file Hibernate runs.

    Thank you
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  7. #7
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    When you open the ear file that is deployed in your jboss deploy, where does the .cfg.xml file appear?
    It needs to be in the root of your classpath.

    Try putting it under src/main/resources/META-INF as well if eclipse is not putting it in the right location.

  8. #8
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    The file shows under JSF-PrimeFaces-SimpleLogin.war\WEB-INF\classes\hibernate.cfg.xml when I use src/main/resources. Here is a printscreen of my Project https://picasaweb.google.com/1000740...57933715932562

    As a side note, I'm using in hibernate.cfg.xml <property name="hibernate.connection.datasource">java:/comp/env/jdbc/MySqlDS</property> shouldn't be <property name="hibernate.connection.datasource">MySqlDS</property>, or <property name="hibernate.connection.datasource">java:MySqlD S</property> ?
    Last edited by buyapentiumjerk; 07-11-2011 at 01:42 PM. Reason: Correct URL
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  9. #9
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Do you still have a persistence.xml file? Because you still need it.

  10. #10
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    No I don't I was thinking to just use hibernate.cfg.xml
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  11. #11
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    So let me see mysql-ds.xml is the place to set connection settings as username and password and server, hibernate.cfg.xml is the place to set hibernate properties and class mappings to DB and finally persistence.xml is the glue between hibernate.cfg.xml and mysql-ds.xml, is this the right way?

    Thank you
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  12. #12
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Class mappings to DB (if you need them at all) should go into your persistence.xml because you want them to be as much unaware of the provider implementation as possible.
    Your persistence xml declares the the JNDI name(s) of the resources that you are going to use for your persistence as well. Remember that hibernate is the implementation and you don't want your application code to be containing too much implementation specific details.
    buyapentiumjerk likes this.

  13. #13
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    Ok r035198x,

    many thanks I got it working now. I ended up with these files:

    persistence.xml

    Java Code:
    <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_2_0.xsd"
    	version="2.0">
    	<persistence-unit name="ejb3-persistence-unit"
    		transaction-type="JTA">
    		<provider>org.hibernate.ejb.HibernatePersistence</provider>
    		<jta-data-source>java:/MySqlDS</jta-data-source>
    		<class>login.UserPOJO</class>
    		<class>login.CompanyPOJO</class>
    	</persistence-unit>
    </persistence>
    hibernate.properties (hibernate.cfg.xml wasn't working, but hibernate.properties does)
    Java Code:
    hibernate.show_sql=true
    hibernate.use_sql_comments=true
    hibernate.format_sql=true
    hibernate.hbm2ddl.auto=update
    Thank you for your help
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  14. #14
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    Hi r035198x,
    I'd like to ask you something else if you don't mind. I now have apparently everything working, my app shows up, my schema gets created/update through Hibernate, but I just can't seem to be able to retrieve Information from DB.

    My output is this:

    Java Code:
    21:33:56,500 INFO  [AbstractJBossASServerBase] Server Configuration:
    
    	JBOSS_HOME URL: file:/C:/JavaDEV/Tools/jboss-6.0.0.Final/
    	Bootstrap: $JBOSS_HOME\server/default/conf/bootstrap.xml
    	Common Base: $JBOSS_HOME\common/
    	Common Library: $JBOSS_HOME\common/lib/
    	Server Name: default
    	Server Base: $JBOSS_HOME\server/
    	Server Library: $JBOSS_HOME\server/default/lib/
    	Server Config: $JBOSS_HOME\server/default/conf/
    	Server Home: $JBOSS_HOME\server/default/
    	Server Data: $JBOSS_HOME\server/default/data/
    	Server Log: $JBOSS_HOME\server/default/log/
    	Server Temp: $JBOSS_HOME\server/default/tmp/
    
    21:33:56,500 INFO  [AbstractServer] Starting: JBossAS [6.0.0.Final "Neo"]
    21:33:58,875 INFO  [ServerInfo] Java version: 1.6.0_26,Sun Microsystems Inc.
    21:33:58,875 INFO  [ServerInfo] Java Runtime: Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
    21:33:58,875 INFO  [ServerInfo] Java VM: Java HotSpot(TM) Client VM 20.1-b02,Sun Microsystems Inc.
    21:33:58,875 INFO  [ServerInfo] OS-System: Windows XP 5.1,x86
    21:33:58,875 INFO  [ServerInfo] VM arguments: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:2422 -Dprogram.name=JBossTools: JBoss 6.0 Runtime -Xms256m -Xmx768m -XX:MaxPermSize=256m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.endorsed.dirs=C:\JavaDEV\Tools\jboss-6.0.0.Final\lib\endorsed -Djava.library.path=C:\JavaDEV\Tools\jboss-6.0.0.Final\bin\native; -Dfile.encoding=Cp1252 
    21:33:58,921 INFO  [JMXKernel] Legacy JMX core initialized
    21:34:05,546 INFO  [AbstractServerConfig] JBoss Web Services - Stack CXF Server 3.4.1.GA
    21:34:06,875 INFO  [JSFImplManagementDeployer] Initialized 3 JSF configurations: [Mojarra-1.2, MyFaces-2.0, Mojarra-2.0]
    21:34:10,562 WARNING [FileConfigurationParser] AIO wasn't located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal
    21:34:14,218 WARNING [FileConfigurationParser] AIO wasn't located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal
    21:34:14,453 INFO  [JMXConnector] starting JMXConnector on host localhost:1090
    21:34:14,671 INFO  [MailService] Mail Service bound to java:/Mail
    21:34:15,984 INFO  [HornetQServerImpl] live server is starting..
    21:34:16,062 INFO  [JournalStorageManager] Using NIO Journal
    21:34:16,078 WARNING [HornetQServerImpl] Security risk! It has been detected that the cluster admin user and password have not been changed from the installation default. Please see the HornetQ user guide, cluster chapter, for instructions on how to do this.
    21:34:16,703 INFO  [NettyAcceptor] Started Netty Acceptor version 3.2.1.Final-r2319 localhost:5445 for CORE protocol
    21:34:16,718 INFO  [NettyAcceptor] Started Netty Acceptor version 3.2.1.Final-r2319 localhost:5455 for CORE protocol
    21:34:16,718 INFO  [HornetQServerImpl] HornetQ Server version 2.1.2.Final (Colmeia, 120) started
    21:34:16,781 INFO  [WebService] Using RMI server codebase: http://localhost:8083/
    21:34:17,031 INFO  [jbossatx] ARJUNA-32010 JBossTS Recovery Service (tag: JBOSSTS_4_14_0_Final) - JBoss Inc.
    21:34:17,046 INFO  [arjuna] ARJUNA-12324 Start RecoveryActivators
    21:34:17,109 INFO  [arjuna] ARJUNA-12296 ExpiredEntryMonitor running at Seg, 11 Jul 2011 21:34:17
    21:34:17,187 INFO  [arjuna] ARJUNA-12310 Recovery manager listening on endpoint 127.0.0.1:4712
    21:34:17,187 INFO  [arjuna] ARJUNA-12344 RecoveryManagerImple is ready on port 4712
    21:34:17,187 INFO  [jbossatx] ARJUNA-32013 Starting transaction recovery manager
    21:34:17,187 INFO  [arjuna] ARJUNA-12163 Starting service com.arjuna.ats.arjuna.recovery.ActionStatusService on port 4713
    21:34:17,218 INFO  [arjuna] ARJUNA-12337 TransactionStatusManagerItem host: 127.0.0.1 port: 4713
    21:34:17,234 INFO  [arjuna] ARJUNA-12170 TransactionStatusManager started on port 4713 and host 127.0.0.1 with service com.arjuna.ats.arjuna.recovery.ActionStatusService
    21:34:17,281 INFO  [jbossatx] ARJUNA-32017 JBossTS Transaction Service (JTA version - tag: JBOSSTS_4_14_0_Final) - JBoss Inc.
    21:34:17,328 INFO  [arjuna] ARJUNA-12202 registering bean jboss.jta:type=ObjectStore.
    21:34:18,250 INFO  [AprLifecycleListener] The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\JavaDEV\Tools\jboss-6.0.0.Final\bin\native;
    21:34:18,437 INFO  [ModClusterService] Initializing mod_cluster 1.1.0.Final
    21:34:18,453 INFO  [TomcatDeployment] deploy, ctxPath=/invoker
    21:34:18,921 INFO  [RARDeployment] Required license terms exist, view vfs:/C:/JavaDEV/Tools/jboss-6.0.0.Final/server/default/deploy/jboss-local-jdbc.rar/META-INF/ra.xml
    21:34:18,937 INFO  [RARDeployment] Required license terms exist, view vfs:/C:/JavaDEV/Tools/jboss-6.0.0.Final/server/default/deploy/jboss-xa-jdbc.rar/META-INF/ra.xml
    21:34:18,953 INFO  [RARDeployment] Required license terms exist, view vfs:/C:/JavaDEV/Tools/jboss-6.0.0.Final/server/default/deploy/jms-ra.rar/META-INF/ra.xml
    21:34:18,968 INFO  [HornetQResourceAdapter] HornetQ resource adaptor started
    21:34:18,968 INFO  [RARDeployment] Required license terms exist, view vfs:/C:/JavaDEV/Tools/jboss-6.0.0.Final/server/default/deploy/mail-ra.rar/META-INF/ra.xml
    21:34:19,000 INFO  [RARDeployment] Required license terms exist, view vfs:/C:/JavaDEV/Tools/jboss-6.0.0.Final/server/default/deploy/quartz-ra.rar/META-INF/ra.xml
    21:34:19,125 INFO  [SimpleThreadPool] Job execution threads will use class loader of thread: Thread-2
    21:34:19,187 INFO  [SchedulerSignalerImpl] Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
    21:34:19,187 INFO  [QuartzScheduler] Quartz Scheduler v.1.8.3 created.
    21:34:19,218 INFO  [RAMJobStore] RAMJobStore initialized.
    21:34:19,234 INFO  [QuartzScheduler] Scheduler meta-data: Quartz Scheduler (v1.8.3) 'JBossQuartzScheduler' with instanceId 'NON_CLUSTERED'
      Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
      NOT STARTED.
      Currently in standby mode.
      Number of jobs executed: 0
      Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
      Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
    
    21:34:19,250 INFO  [StdSchedulerFactory] Quartz scheduler 'JBossQuartzScheduler' initialized from an externally opened InputStream.
    21:34:19,250 INFO  [StdSchedulerFactory] Quartz scheduler version: 1.8.3
    21:34:19,250 INFO  [QuartzScheduler] Scheduler JBossQuartzScheduler_$_NON_CLUSTERED started.
    21:34:20,531 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=DefaultDS' to JNDI name 'java:DefaultDS'
    21:34:20,906 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' to JNDI name 'java:JmsXA'
    21:34:20,937 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=MySqlDS' to JNDI name 'java:MySqlDS'
    21:34:21,218 INFO  [xnio] XNIO Version 2.1.0.CR2
    21:34:21,234 INFO  [nio] XNIO NIO Implementation Version 2.1.0.CR2
    21:34:21,500 INFO  [remoting] JBoss Remoting version 3.1.0.Beta2
    21:34:21,625 INFO  [TomcatDeployment] deploy, ctxPath=/
    21:34:21,687 INFO  [service] Removing bootstrap log handlers
    21:34:21,796 INFO  [org.apache.coyote.http11.Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
    21:34:21,812 INFO  [org.apache.coyote.ajp.AjpProtocol] Starting Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
    21:34:21,812 INFO  [org.jboss.bootstrap.impl.base.server.AbstractServer] JBossAS [6.0.0.Final "Neo"] Started in 25s:312ms
    21:35:02,468 INFO  [org.jboss.web.tomcat.service.deployers.TomcatDeployment] deploy, ctxPath=/JSF-PrimeFaces-SimpleLogin
    21:35:02,484 INFO  [org.apache.catalina.core.StandardContext] The listener "com.sun.faces.config.ConfigureListener" is already configured for this context. The duplicate definition has been ignored.
    21:35:02,531 INFO  [javax.enterprise.resource.webcontainer.jsf.config] Initializing Mojarra 2.0.3 ( b05) for context '/JSF-PrimeFaces-SimpleLogin'
    21:35:05,078 INFO  [javax.enterprise.resource.webcontainer.jsf.config] Monitoring jndi:/localhost/JSF-PrimeFaces-SimpleLogin/WEB-INF/faces-config.xml for modifications
    21:35:15,187 INFO  [org.hibernate.annotations.common.Version] Hibernate Commons Annotations 3.2.0.Final
    21:35:15,218 INFO  [org.hibernate.cfg.Environment] Hibernate 3.6.0.Final
    21:35:15,218 INFO  [org.hibernate.cfg.Environment] hibernate.properties not found
    21:35:15,218 INFO  [org.hibernate.cfg.Environment] Bytecode provider name : javassist
    21:35:15,218 INFO  [org.hibernate.cfg.Environment] using JDK 1.4 java.sql.Timestamp handling
    21:35:15,359 INFO  [org.hibernate.cfg.Configuration] configuring from resource: /hibernate.cfg.xml
    21:35:15,359 INFO  [org.hibernate.cfg.Configuration] Configuration resource: /hibernate.cfg.xml
    21:35:15,375 WARN  [org.hibernate.util.DTDEntityResolver] recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
    21:35:15,375 INFO  [org.hibernate.cfg.Configuration] Configured SessionFactory: SessionFactory
    21:35:15,515 INFO  [org.hibernate.validator.util.Version] Hibernate Validator 4.1.0.Final
    21:35:15,531 INFO  [org.hibernate.validator.engine.resolver.DefaultTraversableResolver] Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    21:35:15,625 INFO  [org.hibernate.validator.engine.resolver.DefaultTraversableResolver] Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    21:35:15,625 INFO  [org.hibernate.cfg.search.HibernateSearchEventListenerRegister] Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
    21:35:15,640 INFO  [org.hibernate.util.NamingHelper] JNDI InitialContext properties:{}
    21:35:15,640 INFO  [org.hibernate.connection.DatasourceConnectionProvider] Using datasource: java:MySqlDS
    21:35:15,906 INFO  [org.hibernate.cfg.SettingsFactory] Database ->
           name : MySQL
        version : 5.5.13
          major : 5
          minor : 5
    21:35:15,906 INFO  [org.hibernate.cfg.SettingsFactory] Driver ->
           name : MySQL-AB JDBC Driver
        version : mysql-connector-java-5.1.17 ( Revision: ${bzr.revision-id} )
          major : 5
          minor : 1
    21:35:15,953 INFO  [org.hibernate.dialect.Dialect] Using dialect: org.hibernate.dialect.MySQLDialect
    21:35:15,984 INFO  [org.hibernate.transaction.TransactionFactoryFactory] Using default transaction strategy (direct JDBC transactions)
    21:35:16,000 INFO  [org.hibernate.transaction.TransactionManagerLookupFactory] No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Automatic flush during beforeCompletion(): disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Automatic session close at end of transaction: disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] JDBC batch size: 15
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] JDBC batch updates for versioned data: disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Scrollable result sets: enabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] JDBC3 getGeneratedKeys(): enabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Connection release mode: auto
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Default schema: test
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Maximum outer join fetch depth: 2
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Default batch fetch size: 1
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Generate SQL with comments: enabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Order SQL updates by primary key: disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Order SQL inserts for batching: disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
    21:35:16,000 INFO  [org.hibernate.hql.ast.ASTQueryTranslatorFactory] Using ASTQueryTranslatorFactory
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Query language substitutions: {}
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] JPA-QL strict compliance: disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Second-level cache: enabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Query cache: disabled
    21:35:16,000 INFO  [org.hibernate.cfg.SettingsFactory] Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Optimize cache for minimal puts: disabled
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Structured second-level cache entries: disabled
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Echoing all SQL to stdout
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Statistics: enabled
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Deleted entity synthetic identifier rollback: disabled
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Default entity-mode: pojo
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Named query checking : enabled
    21:35:16,015 INFO  [org.hibernate.cfg.SettingsFactory] Check Nullability in Core (should be disabled when Bean Validation is on): disabled
    21:35:16,078 INFO  [org.hibernate.impl.SessionFactoryImpl] building session factory
    21:35:16,109 INFO  [org.hibernate.impl.SessionFactoryObjectFactory] Factory name: SessionFactory
    21:35:16,109 INFO  [org.hibernate.util.NamingHelper] JNDI InitialContext properties:{}
    21:35:16,109 INFO  [org.hibernate.impl.SessionFactoryObjectFactory] Bound factory to JNDI name: SessionFactory
    21:35:16,109 WARN  [org.hibernate.impl.SessionFactoryObjectFactory] InitialContext did not implement EventContext
    21:35:16,125 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] Running hbm2ddl schema update
    21:35:16,125 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] fetching database metadata
    21:35:16,125 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] updating schema
    21:35:16,125 INFO  [org.hibernate.validator.engine.resolver.DefaultTraversableResolver] Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    21:35:16,125 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] schema update complete
    When I change Eclipse perspective to Hibernate, under Hibernate Configurations -> Database I get this:

    Java Code:
    org.hibernate.HibernateException: Could not find datasource
    	at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:79)
    	at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:143)
    	at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:84)
    	at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:438)
    	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:91)
    	at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2163)
    	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2159)
    	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1383)
    	at org.hibernate.console.ConsoleConfiguration$4.execute(ConsoleConfiguration.java:241)
    	at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
    	at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:72)
    	at org.hibernate.console.ConsoleConfiguration.buildSessionFactory(ConsoleConfiguration.java:236)
    	at org.hibernate.eclipse.console.workbench.LazySessionFactoryAdapter.getChildren(LazySessionFactoryAdapter.java:43)
    	at org.hibernate.eclipse.console.workbench.BasicWorkbenchAdapter.getChildren(BasicWorkbenchAdapter.java:100)
    	at org.hibernate.eclipse.console.workbench.BasicWorkbenchAdapter.fetchDeferredChildren(BasicWorkbenchAdapter.java:106)
    	at org.eclipse.ui.progress.DeferredTreeContentManager$1.run(DeferredTreeContentManager.java:235)
    	at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
    Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    	at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
    	at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
    	at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
    	at javax.naming.InitialContext.lookup(InitialContext.java:392)
    	at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:75)
    	... 16 more
    Does this means I have to use EntityManager to access my Entities? I'm confused.
    I'm using a DAO, Controller class to retrieve info from DB

    Thank you
    Last edited by buyapentiumjerk; 07-11-2011 at 10:54 PM. Reason: Extra info
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  15. #15
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    I don't know what that pespective is. Why do you need to use that perspective?
    When you build your ear file and deploy it does it access the db values fine?

  16. #16
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    When you install Hibernate tools in Eclipse you get this perspective. I don't have access on my DB although I've inserted them in my DB.

    HibernateUtil.java
    Java Code:
    public class HibernateUtil {
    
    	private static SessionFactory sessionFactory;
    
    	static {
    		try {
    			sessionFactory = new Configuration().configure()
    					.buildSessionFactory();
    		} catch (Throwable ex) {
    			System.err
    					.println("ERROR : Initial SessionFactory creation failed, exception: "
    							+ ex);
    			throw new ExceptionInInitializerError(ex);
    		}
    	}
    
    	public static Session getSession() {
    		return sessionFactory.openSession();
    	}
    }
    GenericDAO.class
    Java Code:
    public class GenericDAO<T extends Serializable> {
    
    	private final Session session;
    	private final Class<T> persistentClass;
    
    	public Session getSession() {
    		return session;
    	}
    
    	public Class<T> getPersistenClass() {
    		return persistentClass;
    	}
    
    	@SuppressWarnings("unchecked")
    	protected GenericDAO() {
    		this.session = HibernateUtil.getSession();
    		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
    				.getGenericSuperclass()).getActualTypeArguments()[0];
    	}
    
    	private void closeSession() {
    		if (getSession() != null && getSession().isOpen()) {
    			getSession().close();
    		}
    	}
    
    	protected void save(T entity) {
    		try {
    			getSession().getTransaction().begin();
    			getSession().save(entity);
    			getSession().getTransaction().commit();
    		} catch (Throwable t) {
    			getSession().getTransaction().rollback();
    			t.printStackTrace();
    		} finally {
    			closeSession();
    		}
    	}
    
    	protected void update(T entity) {
    		try {
    			getSession().getTransaction().begin();
    			getSession().update(entity);
    			getSession().getTransaction().commit();
    		} catch (Throwable t) {
    			getSession().getTransaction().rollback();
    			t.printStackTrace();
    		} finally {
    			closeSession();
    		}
    	}
    
    	protected void delete(T entity) {
    		try {
    			getSession().getTransaction().begin();
    			getSession().delete(entity);
    			getSession().getTransaction().commit();
    		} catch (Throwable t) {
    			getSession().getTransaction().rollback();
    			t.printStackTrace();
    		} finally {
    			closeSession();
    		}
    	}
    
    	@SuppressWarnings("unchecked")
    	protected List<T> findAll() {
    
    // I always get 0 size on getSession().createCriteria(persistentClass).list()
    
    		List<T> teste = getSession().createCriteria(persistentClass).list();
    		System.out.println("GenericDAO: " + Integer.toString(teste.size()));
    		return teste;
    	}
    
    	@SuppressWarnings("unchecked")
    	protected T findById(long id) {
    		return (T) getSession().createCriteria(persistentClass)
    				.add(Restrictions.idEq(id)).uniqueResult();
    	}
    }
    CompanyDAO.java
    Java Code:
    public class CompanyDAO extends GenericDAO<CompanyPOJO> {
    
    	protected void companySave(CompanyPOJO company) {
    		save(company);
    	}
    
    	protected void companyUpdate(CompanyPOJO company) {
    		update(company);
    	}
    
    	protected void companyDelete(int companyId) {
    		CompanyPOJO company = (CompanyPOJO) findById(companyId);
    		delete(company);
    	}
    
    	protected List<CompanyPOJO> companyList() {
    		return findAll();
    	}
    }
    I always get 0 size on getSession().createCriteria(persistentClass).list( ), hence my question about Entity manager. I've used those DAOs under a small SWING app and they worked like a charm, but with J2EE it must have some kind of a problem by using persistence.xml to create the session and mappings(??) and then hibernate.cfg.xml, this is what I'm thinking, maybe Hibernate must take over the session.

    Thank you
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

  17. #17
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    You don't need HibernateUtil when running in an EE container.
    You just inject the PersistenceContext and use the EntityManager for your CRUD operations.
    Java Code:
    @PersistenceContext(unitName = "PU_Name_As_Defined_In_Your_persistence.xml")
    private EntityManager em;
    You don't need to create and manage those transactions as well. All ejb methods will automatically create and commit a transaction for you by default.

    Also, consider making your service layer have a CRUD service rather than make them to be CRUDServices as well. .i.e a Company service uses a CRUD service but is not itself a CRUD service.
    Making them CRUD services has the following disadvantages

    1.) You end up with many empty services just to get CRUD functionality for those entities (Your CompanyDAO above doesn't do anything at all except pass through calls).
    2.) The business service starts getting defined with technical implementation details (A CRUD Service is a technical implementation helper not a business service object).
    3.) Containers pool EJBs so if your container pools ten per EJB and you have 30 entities, you end up with 300 instances in the pool most of which are not being used. Better group your DAOs into one DAOFactory and make that an EJB. That way you have one EJB being pooled and only ten instances most of which are being used.
    Last edited by r035198x; 07-12-2011 at 03:11 PM.
    buyapentiumjerk likes this.

  18. #18
    Join Date
    Apr 2011
    Posts
    36
    Rep Power
    0

    Default

    Ok r035198x, thanks for the info. I'll take it from here.

    Thank you
    There is not knowledge that it is not power!
    buyapentiumjerk.blogspot.com

Similar Threads

  1. Hibernate
    By Freaky123 in forum New To Java
    Replies: 16
    Last Post: 04-19-2011, 05:58 AM
  2. new to hibernate
    By ajhansiprasad in forum Advanced Java
    Replies: 2
    Last Post: 11-06-2008, 05:20 AM
  3. Hibernate Use
    By sireesha in forum JDBC
    Replies: 2
    Last Post: 05-21-2008, 03:05 AM
  4. hibernate
    By vipinpvijayan in forum Web Frameworks
    Replies: 1
    Last Post: 04-21-2008, 05:41 PM
  5. Replies: 2
    Last Post: 06-30-2007, 03:01 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •