How configure TomEE and JPA - mysql

sorry for my bad english, (Im french :-D).
I want work with TomEE for JPA, but my configuration is bad i think.
I receive a exception when i try to connecte to my database (Mysql).
persistence.xml
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>elevage</jta-data-source>
<non-jta-data-source>elevageUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
tomee.xml
<Resource id="elevage" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
DefaultAutoCommit false
</Resource>
<Resource id="elevageUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>
Exception
AVERTISSEMENT: Unexpected exception from beforeCompletion; transaction will roll back
<openjpa-2.4.1-r422266:1730418 fatal general error> org.apache.openjpa.persistence.PersistenceException: user lacks privilege or object not found: OPENJPA_SEQUENCE_TABLE {SELECT SEQUENCE_VALUE FROM OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=-5501, state=42501]
Request is a "SELECT" and i want take all data in my database. I have see documentation but the problem persiste.
Thank all for your answer !
(if you need more file, tell me :-) )

After a long time tearing my hair, I found a solution, if it can save time, here it is:
2 Configurations!
In development:
tomee.xml is not used, it is necessary to configure openejb.xml whose path is specified in the eclipse console, attention, the access is by hidden file
Path for my machine (Linux):
/home/user/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/conf/openejb.xml
At the bottom of the file, you have section "Resource", the configuration is identical to tomee.xml (you can find documentation at this adress : documentation for configuration tomee.xml
In production:
we forget openejb.xml, a configuration is identical but in tomee.xml
to finish, here is my configuration:
persistence.xml
<persistence version="2.0" 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">
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>MyDataBase</jta-data-source>
<non-jta-data-source>MyDataBaseUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<!-- <class>com.test.ejb.BeanUser</class>-->
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
openejb.xml (in development) and tomee.xml (in production)
<Resource id="MyDataBase" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
</Resource>
<Resource id="MyDataBaseUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>

Related

Cannot configure Hibernate with MySQL and TomEE in Java EE (wrong dialect?)

I am learning Java EE and for 2 days already I've been struggling with configuration of Hibernate to work with MySQL database on a TomEE server in a simple Java EE web application.
Hibernate version: 5.4.10.Final (core and entity-manager dependencies)
Java EE API: 8.0
MySQL version: 8.0.19
TomEE version: 8.0.1 (TomEE Embedded in tomee-embedded-maven-plugin)
I have 2 simple entities: Car and Seat, with the uni-directional #OneToMany relation from Car to Seat(s). Color and EngineType are plain enums, while Specification is a value object for these 2 enums). NOTE: FetchType.EAGER is used in the #OneToMany for learning purposes, I am familiar that this is not a good solution normally.
When I try to configure the persistence.xml file, alghouth specifying everything "as for MySQL", it seems that Hibernate still uses the default HSQLDB syntax/dialect/engine and as a result, I recieve errors during schema creation:
[INFO] TomEE embedded started on localhost:8080
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Hibernate: alter table Seat drop foreign key FKkkm9pdx9e1t9jva76n9tqhhqv
mar 06, 2020 1:48:31 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "alter table Seat drop foreign key FKkkm9pdx9e1t9jva76n9tqhhqv" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table Seat drop foreign key FKkkm9pdx9e1t9jva76n9tqhhqv" via JDBC Statement
(...)
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: PUBLIC.SEAT
(...)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: PUBLIC.SEAT // what is going on here???
and for later Hibernate SQL commands while creating DDL, I have also:
Hibernate: create table Car (identifier bigint not null auto_increment, color varchar(255), engineType varchar(255), primary key (identifier)) engine=InnoDB
mar 06, 2020 1:48:31 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "create table Car (identifier bigint not null auto_increment, color varchar(255), engineType varchar(255), primary key (identifier)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table Car (identifier bigint not null auto_increment, color varchar(255), engineType varchar(255), primary key (identifier)) engine=InnoDB" via JDBC Statement
(...)
Caused by: java.sql.SQLSyntaxErrorException: unexpected token: AUTO_INCREMENT
(...)
Caused by: org.hsqldb.HsqlException: unexpected token: AUTO_INCREMENT // definitely something messed up, this is a correct MySQL token
When I omit all "MySQL stuff" (driver and dialect), and make Hibernate use default HSQLDB, it works fine... The DDL for HSQLDB is created well.
I tried many different configurations and replacements googling it over the web and SO, but not found any hint why Hibernate still uses non-MySQL syntax (but I am not 100% sure that this is the direct cause of the issue).
I attempted to specify the datasource in resources.xml file under webapp, but it doesn't change anything. Additionally, I checked if HSQLDB could be excluded from Maven build, but it ships with hibernate-core, so it's not easily achievable and perhaps could also not help.
I have previously used Hibernate with Spring and SpringBoot, but with Java EE I am totally lost here, that's why I asked the question.
Could anyone help with the issue and give some advices on the correct configuration of all this?
My persistence.xml under resources/META-INF looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="my-persistence-unit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:openejb/Resource/myJtaDatabase</jta-data-source>
<!-- Entity classes -->
<class>com.example.javaeecourse.entity.Car</class>
<class>com.example.javaeecourse.entity.Seat</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/javaeecourse?serverTimezone=UTC" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="admin" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="tomee.jpa.factory.lazy" value="true" />
<!--<property name="tomee.jpa.cdi=false" value="false" />-->
</properties>
</persistence-unit>
</persistence>
Car entity:
package com.example.javaeecourse.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import static com.example.javaeecourse.entity.Car.FIND_ALL;
#Getter
#Setter
#Entity
#Table(name = "cars")
#NamedQuery(name = FIND_ALL, query = "SELECT car FROM Car car")
#NoArgsConstructor
public class Car {
public static final String FIND_ALL = "Car.findAll";
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long identifier;
#Enumerated(EnumType.STRING)
private Color color;
#Enumerated(EnumType.STRING)
private EngineType engineType;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "car", nullable = false)
private Set<Seat> seats = new HashSet<>();
}
Seat entity:
package com.example.javaeecourse.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Table(name = "seats")
#NoArgsConstructor
#Getter
#Setter
public class Seat {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String seatMaterial;
public Seat(String seatMaterial) {
this.seatMaterial = seatMaterial;
}
}
CarManufacturer class (#Stateless EJB, where EntityManager is called):
package com.example.javaeecourse.boundary;
import com.example.javaeecourse.control.CarFactory;
import com.example.javaeecourse.entity.Car;
import com.example.javaeecourse.entity.CarCreatedEvent;
import com.example.javaeecourse.entity.Specification;
import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
#Stateless
public class CarManufacturer {
#Inject
CarFactory carFactory;
#Inject
Event<CarCreatedEvent> carCreatedEvent;
#PersistenceContext
EntityManager entityManager;
public Car manufactureCar(Specification specification) {
Car car = carFactory.createCar(specification);
entityManager.persist(car);
carCreatedEvent.fire(new CarCreatedEvent(car.getIdentifier()));
return car;
}
public List<Car> retrieveCars() {
return entityManager.createNamedQuery(Car.FIND_ALL, Car.class).getResultList();
}
}
CarFactory class, which instantiates the entity:
package com.example.javaeecourse.control;
import com.example.javaeecourse.entity.*;
import javax.inject.Inject;
public class CarFactory {
#Inject
#DefaultCarColor
Color randomCarColor;
#Inject
#DefaultCarEngineType
EngineType randomCarEngineType;
public Car createCar(Specification specification) {
Car car = new Car();
car.setColor(specification.getColor() == null ? randomCarColor : specification.getColor());
car.setEngineType(specification.getEngineType() == null ? randomCarEngineType : specification.getEngineType());
Seat seat = new Seat("Leather");
car.getSeats().add(seat);
return car;
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>com.example</groupId>
<artifactId>javaeecourse</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Java EE Course App</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.10.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<finalName>javaeecourse</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<groupId>org.apache.tomee.maven</groupId>
<artifactId>tomee-embedded-maven-plugin</artifactId>
<version>8.0.1</version>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I will be grateful for any help.
Thanks to the hint provided by #areus in the question comment, I was able to resolve the case. I am posting an answer here if anyone had a similar issue in the future.
There was 1 major issue and 1 "bad practice" issue.
The main problem was that I was using a JTA transaction type and referenced the jta-data-source by JNDI name, but the resources.xml was located under webapp instead of resources/META-INF.
After I moved the resource.xml to the META-INF, the database could be properly created and entities were persisted.
Additionally, in my configuration, I have used a deprecated JDBC Driver for MySQL 8. According to this doc, since MySQL 8.0, the driver is now com.mysql.cj.jdbc.Driver, not com.mysql.jdbc.Driver.
I also removed the unnecessary properties, so the config is now quite clear and everything works fine.
resources/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="my-persistence-unit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/javaeecourse</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="tomee.jpa.factory.lazy" value="true"/>
</properties>
</persistence-unit>
</persistence>
resources/META-INF/resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomee>
<Resource id="jdbc/javaeecourse" type="javax.sql.DataSource">
JdbcDriver = com.mysql.cj.jdbc.Driver
JdbcUrl = jdbc:mysql://localhost:3306/javaeecourse?serverTimezone=UTC
UserName = root
Password = admin
jtaManaged = true
</Resource>
</tomee>
Here is also a great article regarding the JTA/RESOURCE_LOCAL transaction types as well as jta-data-source and non-jta-data-source configuration, which helped me understand the details.

Playframework Hibernate JPA cannot connect to Database

I'm trying to configure Hibernate JPA to access database. Without using Hibernate JPA, It accesses to database well, but when using Hibernate JPA it does not.
I'm following this tutorial:
https://www.playframework.com/documentation/2.5.x/JavaJPA
These are my steps:
build.sbt
//Hibernate JPA
libraryDependencies ++= Seq( javaJpa, "org.hibernate" % "hibernate-entitymanager" % "5.1.0.Final" // replace by your jpa implementation )
//JPA
PlayKeys.externalizeResources := false
//Driver for mysql
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.36"
conf/application.conf
db {
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
default.driver = "com.mysql.jdbc.Driver"
default.url = "jdbc:mysql://localhost:3306/sakila"
default.username = root
default.password = "root"
default.jndiName=DefaultDS
jpa.default=defaultPersistenceUnit
default.logSql=true
}
conf/META_INF/persistence.xml
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
</properties>
</persistence-unit>
</persistence>
Error messages:
! #70fdppp3i - Internal server error, for (GET) [/count] ->
play.api.Configuration$$anon$1: Configuration error[Cannot connect to database [jpa]]
at play.api.Configuration$.configError(Configuration.scala:154)
at play.api.Configuration.reportError(Configuration.scala:806)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:48)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42)
at scala.collection.immutable.List.foreach(List.scala:381)
at play.api.db.DefaultDBApi.connect(DefaultDBApi.scala:42)
at play.api.db.DBApiProvider.get$lzycompute(DBModule.scala:72)
at play.api.db.DBApiProvider.get(DBModule.scala:62)
at play.api.db.DBApiProvider.get(DBModule.scala:58)
at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
Caused by: play.api.Configuration$$anon$1: Configuration error[either dataSource or dataSourceClassName is required]
at play.api.Configuration$.configError(Configuration.scala:154)
at play.api.PlayConfig.reportError(Configuration.scala:996)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:70)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:123)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:121)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:142)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:138)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:44)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42)
Caused by: java.lang.IllegalArgumentException: either dataSource or dataSourceClassName is required
at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:785)
at play.api.db.HikariCPConfig.toHikariConfig(HikariCPModule.scala:141)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:57)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:54)
at scala.util.Try$.apply(Try.scala:192)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:54)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:123)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:121)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:142)
Error message on screen:
How to solve it?
I'm using Play framework 2.5
I think your jpa.default property is in wrong place. Try like this:
db {
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
default.driver = "com.mysql.jdbc.Driver"
default.url = "jdbc:mysql://localhost:3306/sakila"
default.username = root
default.password = "root"
default.jndiName=DefaultDS
default.logSql=true
}
jpa.default=defaultPersistenceUnit

How to configure MySQL JTA resource in Spring, JPA and Hibernate for Glassfish v3?

My application is able to perform the read operations but unable to write to the database. How should I configure the JTA transaction manager? I'm using the following: Glassfish 3.1.2.2, Hibernate 4.2.21, Spring 4.2.5, MySQL 5.6 and JDK 1.6. I've tried the following configuration:
persistence.xml
<persistence-unit name="appPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<properties>
<!--<property name="hibernate.transaction.jta.platform"-->
<!--value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>-->
<!--<property name="hibernate.transaction.factory_class" value="org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"/>-->
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
</properties>
</persistence-unit>
web.xml
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/appPersistenceUnit</persistence-unit-ref-name>
<persistence-unit-name>appPersistenceUnit</persistence-unit-name>
</persistence-unit-ref>
applicationContext.xml
<jee:jndi-lookup id="entityManagerFactory"
jndi-name="persistence/appPersistenceUnit"/>
<tx:jta-transaction-manager/>
<tx:annotation-driven/>
MyDAOImpl.java
#PersistenceContext(type = PersistenceContextType.EXTENDED, name = "appPersistenceUnit")
protected EntityManager entityManager;
#Override
public int save(final MyEntity myEntity) {
try {
entityManager.merge(myEntity);
}
catch (Exception e) {
LOGGER.error("Error while saving MyEntity", e);
}
return 1; // id of the created element.
}
On trying to save the entity, I get the following error:
Cannot join transaction: do not override hibernate.transaction.factory_class
Please guide me. What am I doing wrong?

Having connection issue Hibernate 3.0 with MySQL

I am getting this error. I have my hibernate connections and MVC all setup correct I believe.
I heard MySQL drivers have an issue for database connection.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/AdministrativeApplication] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] with root cause
java.sql.SQLException: Unknown database 'testDB'
My hibernate configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Load Hibernate related configuration -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="myroot"/>
<property name="password" value="*****"/>
<!-- connection pooling details -->
<property name="initialSize" value="1"/>
<property name="maxActive" value="5"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<!-- Declare a transaction manager-->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<!-- all the annotation entity classes -->
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
Please let me know what
I could do to resolve this error.
I further added a new java file to test
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "******";
String url = "jdbc:mysql://localhost:3306/testDB";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace(System.out);
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
I get this error . Also I started the MySQL console with this command.
"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
I get this error
java.sql.SQLException: Unknown database 'testdb'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:798)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3700)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1203)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2572)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:15)
Cannot connect to database server
Can some please help resolve this.
i ran netstats no luck. I do not see at what port MySQL is listening at.
Thanks again .
Dhiren
I am getting this error.
This means you did something wrong.
I have my hibernate connections and MVC all setup correct I believe.
See my previous comment - you did not do everything correctly.
I heard MySQL drivers have an issue for database connection.
Nope - MySQL drivers work fine if you set them up properly. You're doing something wrong, and you'll make progress faster if you take that attitude.
Before you run Java, start up the MySQL client, log into MySQL. If you can't, Java won't be able to, either. See if the daemon is up and running.
See if you have that database available. If not, create it.
If it is created, make sure that you have the tables you need and the user you're logging in as has appropriate permissions.
You could create a database named "testDB" in your MySQL instance.

Fluent NHibernate Mapping Exception On Compiling Mapping Document

I have an NHibernate configuration file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="MyProject">
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string_name">MyProject</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
</session-factory>
</hibernate-configuration>
When creating the Configuration object:
Configuration cfg = new Configuration();
cfg.AddFile(nhibernateConfigurationFile);
I'm getting the following errors when trying to run a persistence test:
System.InvalidOperationException: Could not find the dialect in the configuration
NHibernate.MappingException: Could not compile the mapping document: C:\PathToProject\bin\Debug\NHibernateMyProject.config
Anyone know why it is having trouble reading the nhibernate config file? From what I am able to see, the dialect is definitely in the config....
You should use this dialect: NHibernate.Dialect.MsSql2000Dialect
Try to define the assembly which contains the mapping files:
<mapping assembly="yourAssembly"/>
For the configuration file:
new Configuration().Configure( yourfile.cfg.xml );