getting : java.sql.SQLException: Unknown system variable 'language' spring boot - mysql

I am beginning with spring data jpa and i have configured all spring app. in which my bootstrap class is
#SpringBootApplication
#ComponentScan("com.ticket.booking")
#EnableJpaRepositories("com.ticket.booking.dao")
#EntityScan("com.ticket.booking.entity")
public class TicketBookingManagementApplication {
public static void main(String[] args) {
SpringApplication.run(TicketBookingManagementApplication.class, args);
}
}
my controller
#RestController
#RequestMapping(value="/api/ticket")
public class TicketController {
#Autowired
private TicketService ticketService;
#GetMapping(value="/")
public String welcome(){
return "Welcome to Ticket Booking Systems";
}
#PostMapping(value="/add")
public Ticket createTicket(#RequestBody Ticket ticket){
return ticketService.createNewTicket(ticket);
}
#GetMapping(value="/get/{ticketId}")
public Ticket getTicket(#PathVariable ("ticketId") Integer ticketId){
return ticketService.getTicketById(ticketId);
}
}
service and repository
#Service
public class TicketService {
#Autowired
private TicketDao ticketDao;
public Ticket createNewTicket(Ticket ticket) {
// TODO Auto-generated method stub
return ticketDao.save(ticket);
}
public Ticket getTicketById(Integer ticketId) {
// TODO Auto-generated method stub
return ticketDao.findOne(ticketId);
}
}
public interface TicketDao extends CrudRepository<Ticket, Integer>{}
in pom.xml i have added
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
It uses mysql-connector-java-5.1.46.jar:5.1.46 and it maps req successfully but while running app i am getting error like
java.sql.SQLException: Unknown system variable 'language'
and exporting schema to database

update your mysql-connector version. it will solve your problem.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
properties:
spring.datasource.url=jdbc:mysql://localhost/schema_name
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

I am posting this answer because somebody might get benefited from this.
In my case, I was working with Spring-boot so the dependency in pom.xml was
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
So spring boot was taking some default dependency version from Spring boot parent which was different from my System installed mysql-server version 5.1.22 so that was the reason behind that error.
So to resolve this error I overridden the version by specifying manually like below.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
and it worked.

Related

Junit5 Cucumber "No definition found for..." in .feature file

I'm trying to create a simple Junit5-Cucumber project (in Eclipse) that would be used for UI testing.
I took reference from this repo:https://github.com/cucumber/cucumber-java-skeleton
Issue: No definition found for Open the Chrome and launch the application (error happens to the Given, When and Then statements) in the test_features.feature file.
# test_features.feature
Feature: Reset functionality on login page of Application
Scenario: Verification of Reset button
Given Open the Chrome and launch the application
When Enter the username and password
Then Reset the credentials
# RunCucumberTest.java
package lpms.cucumber;
import org.junit.platform.suite.api.ConfigurationParameter;
import org.junit.platform.suite.api.IncludeEngines;
import org.junit.platform.suite.api.SelectClasspathResource;
import org.junit.platform.suite.api.Suite;
import static io.cucumber.junit.platform.engine.Constants.PLUGIN_PROPERTY_NAME;
import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME;
#Suite
#IncludeEngines("cucumber")
#SelectClasspathResource("lpms/cucumber")
#ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty")
#ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "lpms.cucumber")
public class RunCucumberTest {
}
# StepDefinitions.java
package lpms.cucumber;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class StepDefinitions {
#Given("^Open the Chrome and launch the application$")
public void open_the_chrome_and_launch_the_application() throws Throwable
{
System.out.println("This step opens the chrome and launches the application");
}
#When("^Enter the username and password$")
public void enter_the_username_and_password() throws Throwable
{
System.out.println("This step enters the username and password on the login page");
}
#Then("^Reset the credentials$")
public void reset_the_credential() throws Throwable
{
System.out.println("This step clicks on the reset button.");
}
}
Project Structure
IMAGE OF MY PROJECT STRUCTURE
Solved!
It's a warning from Eclipse IDE, likely just a bug, because I can still get testing done.
Sidenote: Extremely useful guide for learning the latest cucumber: https://cucumber.io/docs/guides/10-minute-tutorial/
I had the same problem on my project and i'll post my solution here.
I've used Eclipse + Java 11 + SpringBoot 2.6.4
pom.xml dependencies
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<scope>test</scope>
<version>7.3.0</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit-platform-engine</artifactId>
<version>7.3.0</version>
<scope>test</scope>
</dependency>
pom.xml plugin in build section
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<properties>
<configurationParameters>
cucumber.junit-platform.naming-strategy=long
</configurationParameters>
</properties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
After that, i've created a package in src/test/java called
filelife/skynet/cucumber
In this package i've created my steps class and my runner class; Steps class contains only some logging instrauctions, it doesn't verify nothing yet.
Steps class:
#Slf4j
public class SendMessagesOnServiceLimitsSteps {
#Given("A ServiceLimits Module with PosTXRate of {int} seconds")
public void a_service_limits_module_with_pos_tx_rate_of_seconds(Integer posTxRate) {
log.info("ServiceLimits PosTxRate {}", posTxRate);
System.out.println("Given Step");
}
#When("I keyOn the device")
public void i_key_on_the_device() {
System.out.println("Given Step");
}
#When("i wait for {int} seconds")
public void i_wait_for_seconds(Integer int1) {
System.out.println("Given Step");
}
#When("i keyOff the device")
public void i_key_off_the_device() {
System.out.println("Given Step");
}
#Then("PositionData messages should be {int} or {int}")
public void position_data_messages_should_be_or(Integer int1, Integer int2) {
System.out.println("Given Step");
}
#Then("device log print {string}")
public void device_log_print(String string) {
System.out.println("Given Step");
}
}
And my runner tests class:
#Suite
#IncludeEngines("cucumber")
#SelectClasspathResource("filelife/skynet/cucumber")
#ConfigurationParameter(
key = GLUE_PROPERTY_NAME,
value = "filelife.skynet.cucumber"
)
public class SkynetTest{
}
I've also created the same folder path (filelife/skynet/cucumber) in src/test/resources source folder and i've pasted my .feature file.
In the end, i've created 2 files:
cucumber.properties
junit-platform.properties
in same source folder src/test/resources containg, both of them, string:
cucumber.publish.quiet=true
This configuration works with:
mvn tests
and
right click on SkynetTest -> RunAs -> Junit Test

Spring-boot 2 and swagger 2 (springfox) does not show model

I have created my patch endpoint (Json path specified in RFC 6902).
At UI generated by springfox my endpoint is shown, but the model example (only patch) did not show.
To use Json patch in my Spring-boot 2 project I have used that dependency on pom.xml.
<dependencies>
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-patch</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
At my endpoint, my code is:
#RestController
#RequestMapping(value = "/operation", produces = "application/json")
public class IntentController {
#RequestMapping(value = "/{id}",
method = RequestMethod.PATCH,
consumes = "application/json-patch+json")
public void updateValue(#PathVariable Long id, #RequestBody JsonPatch patch){ {
// ... do magic
}
#RequestMapping(value = "/{id}",
method = RequestMethod.GET)
public MyDto getValue(#PathVariable Long id){ {
MyDto dto = service.findById(id);
return dto;
}
#RequestMapping(method = RequestMethod.POST)
public void updateValue(#RequestBody MyDto dto){ {
service.insert(dto);
}
}
My GET and POST endpoints are generated fine with their example models in UI.
Only PATCH doesn't work fine... their example model didn't generate.
The problem lies with JsonPatch object, this object does not have any getter method, so Springfox library could not generate the model for request.
One possible solution may be like , you create a custom MyJsonPatch POJO with getter and setter and create a JsonPatch with the data of MyJsonPatch.
I can't found a solution to my problem, so I decided to use #ApiParam from Swagger to describe that this field is an RFC 6902 implementation.

hibernate 5 maven and mysql No suitable driver found for jdbc:mysql://127.0.0.1:3306/projeto

i'm getting this error: "No suitable driver found for jdbc:mysql://127.0.0.1:3306/project", i'm using eclipse, maven, hibernate 5, and i've already instaled the mysql connector, but still not working, any ideis?
the prompt error.
GRAVE: Servlet.service() for servlet [Spring MVC Dispatcher Servlet] in
context with path [/projeto] threw exception [Handler dispatch failed; nested
exception is java.lang.ExceptionInInitializerError] with root
causejava.sql.SQLException: No suitable driver found for
jdbc:mysql://127.0.0.1:3306/projeto
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionCreator.makeConnection(DriverManagerConnectionCreator.java:34)
the hiberate and mysql dependencies in my pom file.
<hibernate-core.version>5.0.1.Final</hibernate-core.version>
<hibernate-commons-annotations.version>5.0.1.Final</hibernate-commons-annotations.version>
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>${hibernate-commons-annotations.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
jars on maven
and the code where the error came from. *the code stops in the comented line.
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
.build();
//Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I've found the solution for my problem, but first of all, thanks to Zeromus for answering me. The problem, in my case, is occurring when I'm trying to instantiate this object:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
The method .configure("hibernate.cfg.xml").build(); was not finding the hibernate xml file. I just refreshed the project and the problem was solved, I hope it can help someone. It was so simple, but took a long time to find it.

PowerMockito and Mockito conflict

I need to built unit tests (with junit) for a legacy system. The method that I need to test, makes use of a static method and I need to check if it's called. So, I'll need to use PowerMockito (for "regular" mocking, we use mockito).
But, when I include PowerMockito statements inside the test, Mockito fails with an org.mockito.exceptions.misusing.UnfinishedStubbingException. If I comment the lines PowerMockito.mockStatic(Application.class), PowerMockito.doNothing().when(Application.class) and PowerMockito.verifyStatic(), the UnfinishedStubbingExceptiondoes does not occur, but this way, I'm not able to check if my IllegalArgumentException occured.
The method under test looks like:
public class ClientMB {
public void loadClient(Client client) {
try {
if (client == null) {
throw new IllegalArgumentException("Client is mandatory!");
}
setClient(clientService.findById(client.getId()));
} catch (Exception ex) {
Application.handleException(ex);
}
}
}
And the test looks like:
#PrepareForTest({ Application.class })
#RunWith(PowerMockRunner.class)
public class ClientMBTest {
#Test
public final void testLoadClient() {
ClientService mockedClientService = Mockito.mock(ClientService.class);
Mockito.when(mockedClientService.findById(42L)).thenReturn(new Client());
PowerMockito.mockStatic(Application.class);
PowerMockito.doNothing().when(Application.class);
ClientMB cmb = new ClientMB(mockedClientService);
mb.loadClient(null);
PowerMockito.verifyStatic();
}
}
I imported PowerMokito using the latest version.
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
What I'm doing wrong? Any advice is welcome.
PowerMockito.doNothing().when(Application.class);
That's a stubbing command, but because you don't make a method call after the when(...), it's unfinished.
PowerMockito.doNothing().when(Application.class);
Application.someApplicationMethod();
You need to use this syntax because the normal doVerb().when(foo) syntax will provide an instance, and Java often issues a warning when trying to call a static method based on an instance instead of a class name.
If you want to stub all of Application's methods, you can do so by passing another argument into mockStatic:
PowerMockito.mockStatic(Application.class, RETURNS_SMART_NULLS);

How to configure jackson in spring dispatcher servlet?

I want to send json data to controller in spring.How to configure jackson in dispatcher servlet and which jackson files to add in build path/lib?
You need to add the Jackson dependency first:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version> //your version//
</dependency>
You must add #ResponseBody statement in your code as well. For example:
public class JSONController {
#RequestMapping(value="{name}", method = RequestMethod.GET)
public #ResponseBody Shop getShopInJSON(#PathVariable String name) {
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
return shop;
}
}
Also, add < mvc:annotation-driven /> into your Spring XML configuration file.
You can find a full example of Jackson and Spring in this link.