Skip to content

Commit

Permalink
Change database from mysql to h2
Browse files Browse the repository at this point in the history
  • Loading branch information
sayoungestguy committed Aug 14, 2024
1 parent 11fa481 commit 767a3ec
Show file tree
Hide file tree
Showing 17 changed files with 155 additions and 33 deletions.
Empty file modified .husky/pre-commit
100644 → 100755
Empty file.
4 changes: 2 additions & 2 deletions .yo-rc.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"clientTheme": "none",
"creationTimestamp": 1722041288995,
"databaseType": "sql",
"devDatabaseType": "mysql",
"devServerPort": 9060,
"devDatabaseType": "h2Disk",
"devServerPort": 4200,
"enableHibernateCache": true,
"enableSwaggerCodegen": false,
"enableTranslation": false,
Expand Down
Empty file modified mvnw
100644 → 100755
Empty file.
Empty file modified npmw
100644 → 100755
Empty file.
46 changes: 38 additions & 8 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
<jib-maven-plugin.image>eclipse-temurin:17-jre-focal</jib-maven-plugin.image>
<jib-maven-plugin.version>3.4.3</jib-maven-plugin.version>
<lifecycle-mapping.version>1.0.0</lifecycle-mapping.version>
<liquibase-plugin.driver/>
<liquibase-plugin.hibernate-dialect/>
<liquibase-plugin.password/>
<liquibase-plugin.url/>
<liquibase-plugin.username/>
Expand Down Expand Up @@ -185,10 +187,6 @@
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5-api</artifactId>
Expand Down Expand Up @@ -743,12 +741,12 @@
<configuration>
<changeLogFile>config/liquibase/master.xml</changeLogFile>
<diffChangeLogFile>${project.basedir}/src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
<driver>com.mysql.cj.jdbc.Driver</driver>
<driver>${liquibase-plugin.driver}</driver>
<url>${liquibase-plugin.url}</url>
<defaultSchemaName/>
<username>${liquibase-plugin.username}</username>
<password>${liquibase-plugin.password}</password>
<referenceUrl>hibernate:spring:com.teamsixnus.scaleup.domain?dialect=org.hibernate.dialect.MySQL8Dialect&amp;hibernate.physical_naming_strategy=org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy&amp;hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy</referenceUrl>
<referenceUrl>hibernate:spring:com.teamsixnus.scaleup.domain?dialect=${liquibase-plugin.hibernate-dialect}&amp;hibernate.physical_naming_strategy=org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy&amp;hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy</referenceUrl>
<verbose>true</verbose>
<logging>debug</logging>
<contexts>!test</contexts>
Expand All @@ -774,6 +772,11 @@
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
Expand Down Expand Up @@ -801,8 +804,10 @@
<!-- default Spring profiles -->
<spring.profiles.active>dev${profile.tls}${profile.no-liquibase}</spring.profiles.active>
<profile.test>testdev</profile.test>
<liquibase-plugin.url>jdbc:mysql://localhost:3306/scaleup</liquibase-plugin.url>
<liquibase-plugin.username>root</liquibase-plugin.username>
<liquibase-plugin.hibernate-dialect>org.hibernate.dialect.H2Dialect</liquibase-plugin.hibernate-dialect>
<liquibase-plugin.driver>org.h2.Driver</liquibase-plugin.driver>
<liquibase-plugin.url>jdbc:h2:file:${project.build.directory}/h2db/db/scaleup</liquibase-plugin.url>
<liquibase-plugin.username>scaleup</liquibase-plugin.username>
<liquibase-plugin.password/>
</properties>
<dependencies>
Expand All @@ -811,7 +816,24 @@
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<testExcludes>
<testExclude>com/teamsixnus/scaleup/config/MysqlTestContainer.java</testExclude>
</testExcludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- This is automatically activated when working in Eclipse -->
Expand Down Expand Up @@ -909,6 +931,8 @@
<!-- default Spring profiles -->
<spring.profiles.active>prod${profile.api-docs}${profile.tls}${profile.e2e}${profile.no-liquibase}</spring.profiles.active>
<profile.test>testprod</profile.test>
<liquibase-plugin.hibernate-dialect>org.hibernate.dialect.MySQL8Dialect</liquibase-plugin.hibernate-dialect>
<liquibase-plugin.driver>com.mysql.cj.jdbc.Driver</liquibase-plugin.driver>
<liquibase-plugin.url>jdbc:mysql://localhost:3306/scaleup</liquibase-plugin.url>
<liquibase-plugin.username>root</liquibase-plugin.username>
<liquibase-plugin.password/>
Expand Down Expand Up @@ -986,6 +1010,12 @@
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>tls</id>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,57 @@
package com.teamsixnus.scaleup.config;

import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.h2.H2ConfigurationHelper;

@Configuration
@EnableJpaRepositories({ "com.teamsixnus.scaleup.repository" })
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {}
public class DatabaseConfiguration {

private static final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);

private final Environment env;

public DatabaseConfiguration(Environment env) {
this.env = env;
}

/**
* Open the TCP port for the H2 database, so it is available remotely.
*
* @return the H2 database TCP server.
* @throws SQLException if the server failed to start.
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public Object h2TCPServer() throws SQLException {
String port = getValidPortForH2();
log.debug("H2 database is available on port {}", port);
return H2ConfigurationHelper.createServer(port);
}

private String getValidPortForH2() {
int port = Integer.parseInt(env.getProperty("server.port"));
if (port < 10000) {
port = 10000 + port;
} else {
if (port < 63536) {
port = port + 2000;
} else {
port = port - 2000;
}
}
return String.valueOf(port);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package com.teamsixnus.scaleup.config;

import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;

import com.teamsixnus.scaleup.security.*;
import com.teamsixnus.scaleup.web.filter.SpaWebFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -20,15 +23,19 @@
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;

@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {

private final Environment env;

private final JHipsterProperties jHipsterProperties;

public SecurityConfiguration(JHipsterProperties jHipsterProperties) {
public SecurityConfiguration(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}

Expand Down Expand Up @@ -91,6 +98,9 @@ public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Buil
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
http.authorizeHttpRequests(authz -> authz.requestMatchers(antMatcher("/h2-console/**")).permitAll());
}
return http.build();
}

Expand Down
14 changes: 14 additions & 0 deletions src/main/java/com/teamsixnus/scaleup/config/WebConfigurer.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.config.h2.H2ConfigurationHelper;

/**
* Configuration of web application with Servlet 3.0 APIs.
Expand All @@ -43,6 +46,9 @@ public void onStartup(ServletContext servletContext) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}

if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}

Expand Down Expand Up @@ -93,4 +99,12 @@ public CorsFilter corsFilter() {
}
return new CorsFilter(source);
}

/**
* Initializes H2 console.
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
!path.startsWith("/api") &&
!path.startsWith("/management") &&
!path.startsWith("/v3/api-docs") &&
!path.startsWith("/h2-console") &&
!path.contains(".") &&
path.matches("/(.*)")
) {
Expand Down
6 changes: 6 additions & 0 deletions src/main/resources/.h2.server.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#H2 Server Properties
#Wed Aug 14 23:11:21 SGT 2024
0=JHipster H2 (Disk)|org.h2.Driver|jdbc\:h2\:file\:./target/h2db/db/scaleup|scaleup
webAllowOthers=true
webPort=8092
webSSL=false
17 changes: 8 additions & 9 deletions src/main/resources/config/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,24 @@ spring:
devtools:
restart:
enabled: true
additional-exclude: static/**
additional-exclude: static/**,.h2.server.properties
livereload:
enabled: false # we use Webpack dev server + BrowserSync for livereload
jackson:
serialization:
indent-output: true
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/scaleup?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&createDatabaseIfNotExist=true
username: root
url: jdbc:h2:file:./target/h2db/db/scaleup;DB_CLOSE_DELAY=-1;MODE=MYSQL
username: scaleup
password:
hikari:
poolName: Hikari
auto-commit: false
data-source-properties:
cachePrepStmts: true
prepStmtCacheSize: 250
prepStmtCacheSqlLimit: 2048
useServerPrepStmts: true
h2:
console:
# disable spring boot built-in h2-console since we start it manually with correct configuration
enabled: false
liquibase:
# Remove 'faker' if you do not want the sample data to be loaded automatically
contexts: dev, faker
Expand Down Expand Up @@ -73,7 +72,7 @@ jhipster:
# CORS is only enabled by default with the "dev" profile
cors:
# Allow Ionic for JHipster by default (* no longer allowed in Spring Boot 2.4+)
allowed-origins: 'http://localhost:8100,https://localhost:8100,http://localhost:9000,https://localhost:9000,http://localhost:9060,https://localhost:9060'
allowed-origins: 'http://localhost:8100,https://localhost:8100,http://localhost:9000,https://localhost:9000,http://localhost:4200,https://localhost:4200'
# Enable CORS when running in GitHub Codespaces
allowed-origin-patterns: 'https://*.githubpreview.dev'
allowed-methods: '*'
Expand Down
6 changes: 6 additions & 0 deletions src/main/resources/config/liquibase/master.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<property name="now" value="now()" dbms="h2"/>
<property name="floatType" value="float4" dbms="h2"/>
<property name="uuidType" value="varchar(36)" dbms="h2"/>
<property name="datetimeType" value="datetime(6)" dbms="h2"/>
<property name="clobType" value="clob" dbms="h2"/>
<property name="blobType" value="blob" dbms="h2"/>
<property name="now" value="now()" dbms="mysql"/>
<property name="floatType" value="float" dbms="mysql"/>
<property name="clobType" value="clob" dbms="mysql"/>
Expand Down
4 changes: 3 additions & 1 deletion src/main/webapp/app/shared/layout/header/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ const Header = (props: IHeaderProps) => {
<Nav id="header-tabs" className="ms-auto" navbar>
<Home />
{props.isAuthenticated && <EntitiesMenu />}
{props.isAuthenticated && props.isAdmin && <AdminMenu showOpenAPI={props.isOpenAPIEnabled} />}
{props.isAuthenticated && props.isAdmin && (
<AdminMenu showOpenAPI={props.isOpenAPIEnabled} showDatabase={!props.isInProduction} />
)}
<AccountMenu isAuthenticated={props.isAuthenticated} />
</Nav>
</Collapse>
Expand Down
10 changes: 9 additions & 1 deletion src/main/webapp/app/shared/layout/menus/admin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,18 @@ const openAPIItem = () => (
</MenuItem>
);

export const AdminMenu = ({ showOpenAPI }) => (
const databaseItem = () => (
<DropdownItem tag="a" href="./h2-console/" target="_tab">
<FontAwesomeIcon icon="database" fixedWidth /> Database
</DropdownItem>
);

export const AdminMenu = ({ showOpenAPI, showDatabase }) => (
<NavDropdown icon="users-cog" name="Administration" id="admin-menu" data-cy="adminMenu">
{adminMenuItems()}
{showOpenAPI && openAPIItem()}

{showDatabase && databaseItem()}
</NavDropdown>
);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.teamsixnus.scaleup.config;

import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -11,6 +12,7 @@
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextCustomizerFactory;
import org.springframework.test.context.MergedContextConfiguration;
import tech.jhipster.config.JHipsterConstants;

public class SqlTestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory {

Expand All @@ -26,7 +28,10 @@ public void customizeContext(ConfigurableApplicationContext context, MergedConte
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
TestPropertyValues testValues = TestPropertyValues.empty();
EmbeddedSQL sqlAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedSQL.class);
if (null != sqlAnnotation) {
boolean usingTestProdProfile = Arrays.asList(context.getEnvironment().getActiveProfiles()).contains(
"test" + JHipsterConstants.SPRING_PROFILE_PRODUCTION
);
if (null != sqlAnnotation && usingTestProdProfile) {
log.debug("detected the EmbeddedSQL annotation on class {}", testClass.getName());
log.info("Warming up the sql database");
if (null == prodTestContainer) {
Expand Down
Loading

0 comments on commit 767a3ec

Please sign in to comment.