Connecting to mysql database as a data source in eclipse web app - mysql

I can connect to the embedded h2 database, but am confused about the correct syntax for connecting to a mysql database named 'test1'. For example, I would like to know what to substitute in the pom.xml, web.xml and persistence.xml files instead of the h2 terminology.
I'm using mysql 5.7.27, with mysql-connector-java-8.0.27.jar in my src/main/resources/META-INF/lib folder. My url is jdbc:mysql://localhost:3306/test1
pom.xml - what to use for groupId and artifactId
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2></artifactId>
<version>1.4.200</version>
</dependency>
web.xml - what to use for name and class
<data-source>
<name>java:global/DataSourceName>
<class-name>org.h2.jdbcx.JdbcDataSource</class-name>
<url>jdbc:h2:mem;DB_CLOSE_DELAY=-1</url>
</data-source>
persistence.xml - does this need to change
<persistence-unit name="PersistenceUnitName"
transaction-type="JTA">
<jta-data-source>java:global/DataSourceName</jta-data-source>
<properties>
<property
name="javax.persistence.schema-generation.database.action"
value="none" />
</properties>
</persistence.unit>
</persistence>

follow this Guide to configure all things you need to connect to MySQL or MariaDB.Use the bellow configuration for MySQL.
- in step (1) use The right classname of MySQl DataSource as bellow:
datasource-classname="com.mysql.cj.jdbc.MysqlDataSource"
Ref: MySQL Doc - Configuration Properties
- In step (3) Add this in POM.XML:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>x.y.z</version>
</dependency>
Ref: MySQL Doc - Installing MySQL Connector/J Using Maven

Related

Hibernate db url configuratin issue with UTC mapping

Getting below error message while configuring db details in hibernate.cfg.xml file.
Sensing a mistake in jdbc url, But not able to find the actual cause.
Caused by: com.mysql.cj.exceptions.WrongArgumentException: No timezone
mapping entry for
'UTC;allowPublicKeyRetrieval=true;useLegacyDatetimeCode=false' at
snippet of hibernate.cfg.xml file
<!-- JDBC Database connection settings -->
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC;allowPublicKeyRetrieval=true</property>
Using below tag
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
and replacing javax.persistance with latest maven version helped me. maven entry as below
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>

How to connect Spring Boot Application with MySQL database?

I am new at spring framework, I want to connect my MySQL database which located in localhost with spring boot application.
I'm listing out the minimal configuration:
In pom.xml
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
In application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
You can get such examples everywhere. Prefer to read https://spring.io/guides/gs/accessing-data-mysql/
Source : https://spring.io
Checkout other questions too :
How to use Spring Boot with MySQL database and JPA?
Spring Boot MYSQL connection
Spring boot - MySQL settings are not working
You need to add database configuration properties for Mysql in your application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=mysql
spring.datasource.password=mysql
spring.jpa.hibernate.ddl-auto=create this configuration will create tables based on your entities which were created by you.
spring.datasource.url=jdbc:mysql://localhost:3306/db_example this configuration connects through jdbc to your database called db_example. You need to create that database.
spring.datasource.username=mysql this configuration you need to put your user who will connect via jdbc to your mysql database.
spring.datasource.password=mysql this configuration you need to provide your password which is represented by your user in order to connect through jdbc to your mysql database.
In addition tou you need to add dependencies for Mysql and JPA.
If you are using maven, add the dependencies in your pom.xml:
<dependencies>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
If you are using gradle, add the dependencies in build.gradle:
dependencies {
// JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
// Use MySQL Connector-J
compile 'mysql:mysql-connector-java'
}
Add below dependencies in pom.xml.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Add below database properties in application.properties.
spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=root
spring.datasource.password=root
For more details please refer this link
To connect with mysql need some dependencies as below
Dependencies (maven -> pom.xml).
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
in application.properties need some extra configuration setting which must like like
application.properties (src/main/resources/application.properties)
# DataSource settings: set here your own configurations for the database
# connection. In this example we have "netgloo_blog" as database name and
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:8889/database_name
spring.datasource.username = mysql-userId
spring.datasource.password = mysql-pwd
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy (Not necessary to add but you can use this too)
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Now your EntityManager Object will be constructed when you starts your spring boot Configuration.
Above defined configuration is enough to connect your local my-sql database but here is some more configuration that you need to make your code more readable.
Enable JPARepositories such that CRUD Repositories must defined in a defined package.
Add #EnableJPARepositories("basepackage.*") to your SpringBootMainApplicationClass like this..
#SpringBootApplication
#EnableJPARepositories("com.demo.application.*.repositories")
#ComponentScan("com.demo.application.*")
public class SpringBootMainApplicationClass {
public static void main(String[] args) {
SpringApplication.run(SpringBootMainApplicationClass.class, args);
}
}
by adding #EnableJPARepositories Annotation in MainClass enables user to make your code more readable and EntityManager Object only restricted to only defined package.
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/jpa
spring.datasource.username = root
spring.datasource.password =
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
build.gradle
implementation 'mysql:mysql-connector-java:8.0.15'

Set JSON provider at RESTEasy on JBoss 7.1.1

How could I set JSON provider for RestEasy at JBoss 7.1.1?
RestEasy documentation says:
RESTEasy allows you to marshall JAXB annotated POJOs to and from JSON.
This provider wraps the Jettison JSON library to accomplish this.
But I found that it seems that on JBoss 7.1.1 Resteasy uses Jackson provider because #XmlTransient on my class field was ignored, but #JsonIgnore was processed.
How can I tell to Resteasy to use Jettison instead of Jackson?
On Jboss I found both providers.
if you just want to have a different module pulled than the standard, you can provide this in a jboss specific deployment descriptor.
Read https://docs.jboss.org/author/display/AS71/Class+Loading+in+AS7 to learn the details, and read https://docs.jboss.org/author/display/AS7/Implicit+module+dependencies+for+deployments to learn what modules JBoss uses by default.
To exchange the two providers, provide a META-INF/jboss-deployment-structure.xml with the following content below.
This switched the provider for me.
Br Alexander.
<jboss-deployment-structure>
<deployment>
<exclusions>
<module name="org.jboss.resteasy.resteasy-jackson-provider" />
</exclusions>
<dependencies>
<module name="org.jboss.resteasy.resteasy-jettison-provider" />
</dependencies>
</deployment>
</jboss-deployment-structure>
As a follow-on to ahus1's answer: if you have a multi-level deployment archive (i.e. a top-level EAR file containing an EJB jar and a war file), you will need to configure the exclusion of org.jboss.resteasy.resteasy-jackson-provider on whichever sub-deployment contains the RESTEasy/JAX-RS components.
In my deployment, for example, my REST endpoints were annotated on top of EJBs in my EJB jar file, while my #ApplicationPath-annotated javax.ws.rs.core.Application subclass which activates RESTEasy was in my war file. I found that the approaches of putting the exclusions solely on the top-level (EAR) deployment (as in ahus1's example) or on the EJB-jar-level deployment were ineffective, but I finally got RESTEasy to use Jettison rather than Jackson by putting the exclusions on all 3 levels (EAR, EJB, Web):
<?xml version="1.0" encoding="UTF-8" ?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
<deployment>
<exclusions>
<module name="org.jboss.resteasy.resteasy-jackson-provider" />
</exclusions>
<dependencies>
<module name="org.jboss.resteasy.resteasy-jettison-provider" />
</dependencies>
</deployment>
<sub-deployment name="MyApp-ejb.jar">
<exclusions>
<module name="org.jboss.resteasy.resteasy-jackson-provider" />
</exclusions>
<dependencies>
<module name="org.jboss.resteasy.resteasy-jettison-provider" />
</dependencies>
</sub-deployment>
<sub-deployment name="MyApp.war">
<exclusions>
<module name="org.jboss.resteasy.resteasy-jackson-provider" />
</exclusions>
<dependencies>
<module name="org.jboss.resteasy.resteasy-jettison-provider" />
</dependencies>
</sub-deployment>
</jboss-deployment-structure>
It's very likely that I only needed the exclusions on the subdeployments, and putting it on the main EAR deployment is superfluous; I didn't try it that way, since for now putting it on all three seems to work perfectly well.
From what I observed right now, Jackson is the default in JBoss AS 7.1.2.
First, the RestEasy modules are hidden from app's classloader, which IMO should not be.
So I just filed https://issues.jboss.org/browse/AS7-5605 .
Second, to your question: To set the particular provider, you need to remove it from classloader's spot in AS - so again, to go module.xml's and comment out those providers which you don't want to use - if Jackson is available, RestEasy uses it; otherwise it uses Jettison.
Also, add them your project as a compile time dependency, so you can use their specific annotations. Example:
<!-- RestEasy -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>2.3.4.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.2</version>
<scope>provided</scope>
</dependency>
Note: Until AS7-5605 is done, you need to set the versions manually.
After (in later versions of AS), you have to remove these versions and use those defined in JBoss BOM. See JBoss AS QuckStarts for example.
Feel free to create and contribute a QuickStart of RestEasy using alternative provider.
I added this line to standalone.conf.bat/sh and it solved my problem.
set "JAVA_OPTS=%JAVA_OPTS% -Dcom.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager=true"

jetty-env.xml with DataSource leads to failing WebAppContext on mvn jetty:run

I have a really simple webapp project with maven and jetty that has been working very well until now. But now I need to setup MySQL connection pooling with JNDI as the database connections always time out.
First of all here is the relevant content of my pom.xml:
<modelVersion>4.0.0</modelVersion>
...
<packaging>war</packaging>
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty-version>8.1.0.v20120127</jetty-version>
</properties>
<dependencies>
...
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
...
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
</configuration>
</plugin>
</plugins>
...
</build>
Now I created a jetty-env.xml in the folder /src/main/webapp/WEB-INF with the following content:
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<New id="project-db" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>jdbc/db</Arg>
<Arg>
<New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<Set name="url">jdbc:mysql://www.example.com:3306/mydb</Set>
<Set name="username">dbuser</Set>
<Set name="password">dbpass</Set>
</New>
</Arg>
</New>
</Configure>
But the problem is that I can't even test if this connection works as the jetty-maven-plugin fails to start on the goal
mvn jetty:run
with the following error:
WARN:oejw.WebAppContext:Failed startup of context o.m.j.p.JettyWebAppContext
{/,file:/D:/documents/programmierung/workspace/battleships-trunk/src/main/webapp/}
,file:/D:/documents/programmierung/workspace/battleships-trunk/src/main/webapp/
java.lang.IllegalArgumentException: Object of class
'org.mortbay.jetty.plugin.JettyWebAppContext' is not of type
'org.eclipse.jetty.webapp.WebAppContext'.
Object Class and type Class are from different loaders.
So how can I get this to work? I'm forced to use Jetty version 8.x as I need WebSocket support and as the remote productive server will be running Jetty 8.
EDIT
Before Pavel Veller's answer I tried the following: Deployed the assembled war to the remote jetty8 server and got the same error only that the previous error now reads as follows:
java.lang.IllegalArgumentException: Object of class
'org.eclipse.jetty.webapp.WebAppContext' is not of type
'org.eclipse.jetty.webapp.WebAppContext'.
Object Class and type Class are from different loaders.
So it seems as if there are multiple class loaders conflicting.
EDIT2
As requested by Pavel I recreated the error with a simplified webapp which you can find here on Dropbox. It is a zipped eclipse maven project.
Try removing the dependency on jetty-maven-plugin- this dependency adds the plugin to the WAR, which you don't want.
If you need to use any classes from Jetty itself, add a dependency for the specific version of Jetty (rather than the plugin) with a scope of provided.
It looks like it's pulling jetty 6 from somewhere. The exception you're seeing seems to be coming from the code that parses jetty-env.xml (org.mortbay.jetty.plus.webapp.EnvConfiguration). The XMLConfiguration class compares the class you declare on the Configure element with the actual class of what it gets from getWebAappContext(). The latter is instance of org.mortbay.jetty.plugin.JettyWebAppContext in your case and you expect it to be org.eclipse.jetty.webapp.WebAppContext (which would be the parent class for JettyWebAppContext had they both come from the same "namespace").
It's hard to tell where that would be happening from but maybe inspect your .m2 and confirm you have the proper binaries for your jetty dependencies? It has got to be running not the version you expect it to run.
UPDATE. Jetty does the following when it loads the classes defined in the configuration:
first load with Thread.currentThread().getContextClassLoader() and
loop through all getParent() until all options are exhausted.
if not successful, attempt to load with the class loader that loaded
jetty core classes (XmlConfiguration.class.getClassLoader())
looping through all the parents as well.
If still not successful, do a Class.forName()
Report ClassNotFoundException if not successful.
you can see it in the code of org.mortbay.util.Loader(http://grepcode.com is a great resource for a quick look under the hood)
It does load the class in your case, but apparently not with the right class loader.
I would now assume you have an extra jetty JAR somewhere on your classpath that interferes with the order of things.
Had a same issue caused by :
<useTestClasspath>true</useTestClasspath> (true instead of false)
That put a extra jetty jar in the classpath...
Including the dependency scope solved the error for me.
<scope>provided</scope>
In the pom.xml it looks like this,
<!-- JETTY DEPENDENCIES -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
in the jetty dependencies and the errors went off. And btw, the jetty version I'm using is 9.3.7.v20160115.
I had the same issue and fixed it but can't figure out why.
By changing
org.eclipse.jetty.webapp.WebAppContext
to
org.eclipse.jetty.maven.plugin.JettyWebAppContext
it started to work for some reason, can't figure out exactly why. Clearly maven plugin has something to do with it?

maven tomcat plugin with mysql driver in $catalina_home/lib

i am trying to use a container managed datasource (via context.xml) in tomcat. The corresponding jar file needs to go in $catalina_home/lib, otherwise tomcat can't find it. (not in webapp/WEB-INF/lib, because it is managed by the webserver, not by the application itself)
the problem is: I am using maven with the maven-tomcat-plugin, so I don't have a $catalina_home (everything is distributed in my .m2 -repository).
So the question is: how can I add the mysql driver jar to the classpath of the tomcat server (mvn tomcat:run)?
thanks a lot,
gerolf.
Did you try to add the JDBC driver as a dependency of the maven-tomcat-plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
...
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
</dependencies>
</plugin>