Use mysql instead hsql java spring - java

I hava this codes and i use application.properties for use mysql but yet hsql is use.
application.properties
spring.datasource.url=jdbc:mysql://localhost:3307/dvv
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.platform=mysql
and application.class
#EnableAutoConfiguration
#EnableJpaRepositories(basePackageClasses = {VideoRepository.class, VideoRepository2.class})
#Configuration
#EnableWebMvc
#ComponentScan
public class Application {
// Tell Spring to launch our app!
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and Repository
#Repository
public interface VideoRepository2 extends CrudRepository<Video2, Long>{
// Find all videos with a matching title (e.g., Video.name)
public Collection<Video2> findByName(String title);
// Find all videos within a given category
public Collection<Video2> findByCategory(String category);
}

Can you verify,
1.Check how many application-XXX.properties files are exists in your application.
2.Check whether you are using correct profile to run this application.
Also share your hsql configuration as well.

make sure the mysql connector is added to your pom.xml /build.gradle
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

Related

Sending Email using VSCode (spring-boot-starter-email)

I am implementing how to send email using spring boot
I am trying to implement this in visual studio code.
But it gives me the following error
I added the following two dependencies in my pom.xml for email configuration:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
my main bootstrap class:
#SpringBootApplication
#ComponentScan(basePackages = {
"email"
})
public class Application {
public static void main(String[] args) {
Mail mail = new Mail();
mail.setMailFrom("abc#gmail.com");
mail.setMailTo("xyz#gmail.com");
mail.setMailSubject("Hi");
mail.setMailContent("Hope you are doing well");
ApplicationContext ctx = SpringApplication.run(Application.class,
args);
MailService mailService = (MailService) ctx.getBean("mailService");
mailService.sendEmail(mail);
}
I think my error is related to the #ComponentScan(basePackages = {"email"}) annotation that I have used above
Can anyone help me with the error?
Since we don't know the package structure it is difficult to tell what should be there in the basePackages inside #ComponentScan
Firstly, please move your Application class to one level up in the package structure, so that it reads all packages under it by default and remove the basePackages in component scan. So, it should be just #ComponentScan
That is, if all your classes are in package com.test.mailer then your Application class file should be in com.test
Try this and let us know, also I hope you have the #Service annotation as #Service("mailService")
Update:
Since the user has updated the question later, I am posting the solution that worked for him.
He moved the class one level up and removed the basePackages and it worked for him. As stated in the first part of my answer.
Alternatively, he could have changed #ComponentScan(basePackages = {"email"}) to #ComponentScan("java.risknucleus") in the same structure.

Accessing static files outside of the application folder using Spring Boot 2.2

In our application, we have to serve static files from a folder outside of the application folder. The location of the static file folder is /var/tmp/myapp/attachments additionally to the default locations. The application is implemented to create a deployable war (extending SpringBootServletInitializer.class). Using Spring Boot 2.2 and Tomcat 9
Here is the setup of my application:
1. application.yml file
main:
web-application-type: none
# tried adding static resource location here but did not work
#resources:
#static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:///var/tmp/myapp/attachments/
2. Application.class
#SpringBootApplication(
// We are including Spring, but don't want it to stomp on the legacy servlet container, so disable various configurations.
exclude = {
DispatcherServletAutoConfiguration.class,
ErrorMvcAutoConfiguration.class,
WebMvcAutoConfiguration.class,
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class},
scanBasePackages = {"com.app", "com.appmodule"})
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
3. pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Tried Solutions:
1. Tried to add spring-resources-static-locations to application.yml
2. Tried to write:
#Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/myapp/**")
.addResourceLocations("classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:///var/tmp/myapp/attachments/");
}
}
The link created to access static locations:
1. http://my.development.com:8080/myapp/attachments/6b8f6b78-e0e3-4163-89df-2861ac58bc65/common/images/COVER_PANE_FOOTER_COMPANY_LOGO/11/CompanyLogo.jpg
2. also tried: http://my.development.com:8080/attachments/6b8f6b78-e0e3-4163-89df-2861ac58bc65/common/images/COVER_PANE_FOOTER_COMPANY_LOGO/11/CompanyLogo.jpg
Could you please help me figure out based on current application configuration what is the best way to achieve it?
Thank you!

Getting directed to 404 page in Spring Boot backend

I am working on Spring Boot application. I have my jsp frontend and my java backend. When I up the project in tomcat server I can see the frontend get upped. But when I try to direct the url to check the backend performance I am getting directed to 404.
Example http://localhost:8090/orders
#RequestMapping paths were defined in the correct way.I am using workbench in my case.
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/csse_ass
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=create
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
pom.xml (I have so many dependencies, I add the essential one here)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
controller
private OrderService orderService;
#RequestMapping("/orders")
public List<Order> getAllOrders(){
return orderService.getAllOrders();
}
service
#Autowired
private OrderRepository orderRepository;
public List<Order> getAllOrders(){
List<Order> orders = new ArrayList<>();
for (Order order : orderRepository.findAll()) {
orders.add(order);
}
return orders;
}
repository
public interface OrderRepository extends CrudRepository<Order,String> {}
As well as I have my order.java class.I hope it doesn't matter in this problem.
I get no errors in my terminal except the tomcat errors which is common.
Question
Why I am getting directed to 404 page as I mentioned in the very top of the question?
Somebody fix this issue for me, cuz I couldn't figure out the problem.
try this...
#RequestMapping("/orders")
#ResponseBody
public List<Order> getAllOrders(){
return orderService.getAllOrders();
}
use #Controller annotation also..

Unable to add external JDBC jar file to Spring Boot, despite adding it to application.properties

I tried following the instructions mentioned here to add a driver for the SAP HANA database. The driver is available as a jar file, and had been added to the pom.xml:
<dependency>
<groupId>com.sap.db.jdbc</groupId>
<artifactId>ngdbc</artifactId>
<version>1.96.0</version>
</dependency>
My application properties was as follows:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:sap://<YOUR SAP HANA IP>:host
spring.datasource.username=sap_hana_user
spring.datasource.password=sap_hana_password
spring.datasource.driver-class-name=com.sap.db.jdbc.Driver
However, that didn't work, and I was still getting the error message:
Cannot determine embedded database driver class for database type NONE.
What did work, was adding the Datasource programmatically, as mentioned here, and removing the application.resources file. So, finally, my Application.java looks like:
#SpringBootApplication
public class Application extends SpringBootServletInitializer
{
#Bean
#Primary
public DataSource dataSource()
{
return DataSourceBuilder.create().username("user_name_sap_hana").password("password_sap_hana").url("jdbc:sap://<YOUR SAP HANA IP>:port").driverClassName("com.sap.db.jdbc.Driver").build();//https://stackoverflow.com/a/28822145/1243462 ; https://stackoverflow.com/a/1336965/1243462
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(Application.class);
}
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
Could someone please explain what I did wrong? The first method did not mention having to do anything besides enter these details in application.resources.

Second datasource in spring application.properties for tests?

I have datasource defined in my application.properties as Oracle database and that's ok, the controller & repository work fine, I can persist entities and fetch database records.
I have integration tests written. Before I connected my app with database I created some objects and persisted them in #PostConstruct method - and that was ok. But now, when I connected everything with database, my tests try to fetch records from the table which is pretty large.
I think that's due to my application.properties file in which defined datasource is Oracle database.
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#blabla
spring.datasource.username=blabla
spring.datasource.password=blabla
spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=false
I want to carry on tests using some in-memory HSQL, not real database. But I still want my controller and repository to use the real one. How can I do it? Is there any possibility to add second datasource in application.properties? Or maybe an easier solution?
In Spring 4 you have #Profile annotation so you can use its advantage.
Create another like application-test.properties file with it's own properties.
Create configuration for your tests:
#Configuration
#Profile("test")
public class TestConfiguration {
....
}
Then annotate your class with #ActiveProfiles annotation:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = TestConfiguration.class)
#ActiveProfiles("test")
public class TestRepository {
...
}
There are many ways to achieve this, one way is to use Spring profiles. The test profile would use a different properties file than the production one.
Spring has org.springframework.mock.jndi.SimpleNamingContextBuilder package that allows you to bind the dataSource programatically.
Sample Test class that I use:
public class MockJNDIContext {
#BeforeClass
public static void setUpClass() throws Exception {
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();//Use your own Connection Pool DS here as you require
ds.setURL("jdbc:oracle:thin:#10.xxx.xxx.xx:9999:SID");
ds.setUser("USER");
ds.setPassword("PASSWORD");
//Bind it to the JNDI you need
builder.bind("java:comp/env/jdbc/MY/APP", ds);
}
#Test
public void test(){
System.out.println("JNDI Initialized");
}
}
Suite Class:
#RunWith(Suite.class)
#Suite.SuiteClasses({
MockJNDIContext.class,
InitializeTestConfig.class
})
public class ServiceSuite{
}
May be this helps? If you are trying to load from one more application.props, use one more class (InitializeTestConfig.class) that initializes and passes the DS args and add to suite as mentioned above and try?

Categories