Why Spring Boot Test initialize DataSource many times? - spring-boot

I used this configuration for database initiation in code.
But when I start the unit test, the database will be initialized many times.
I am not sure if this is correct. Because sometimes I will get some error response from Database.
This configuration PrimaryDataSourceConfiguration contains all the database-related beans.
#Configuration
#EnableJpaRepositories(
basePackages = {"com.test.core.infrastructure.datasource.primary.repo"},
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager"
)
#EnableTransactionManagement
public class PrimaryDataSourceConfiguration {
#Bean("primaryDataSource")
#Primary
#ConfigurationProperties("test.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
#Bean("primaryJdbcTemplate")
#Primary
public JdbcTemplate primaryJdbcTemplate(#Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean("primaryEntityManagerFactory")
#Primary
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
#Qualifier("primaryDataSource") DataSource primaryDataSource,
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.packages("com.test.core.infrastructure.datasource.primary.entity")
.persistenceUnit("myDS")
.build();
}
#Bean("primaryTransactionManager")
#Primary
public PlatformTransactionManager primaryTransactionManager(
#Qualifier("primaryEntityManagerFactory") LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory) {
return new JpaTransactionManager(primaryEntityManagerFactory.getObject());
}
}
2022-06-10 18:48:29.070 INFO 21772 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'myDS'
2022-06-10 18:48:29.073 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-06-10 18:48:29.079 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2022-06-10 18:48:29.084 INFO 21772 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'myDS'
2022-06-10 18:48:29.086 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown initiated...
2022-06-10 18:48:29.157 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown completed.
2022-06-10 18:48:29.159 INFO 21772 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'myDS'
2022-06-10 18:48:29.160 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-3 - Shutdown initiated...
2022-06-10 18:48:29.213 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-3 - Shutdown completed.
2022-06-10 18:48:29.214 INFO 21772 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'myDS'
2022-06-10 18:48:29.215 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-4 - Shutdown initiated...
2022-06-10 18:48:29.263 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-4 - Shutdown completed.
2022-06-10 18:48:29.266 INFO 21772 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'myDS'
2022-06-10 18:48:29.268 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Shutdown initiated...
2022-06-10 18:48:29.358 INFO 21772 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Shutdown completed.

Related

JPA ColumnTransformer write is not working

this is my entity.
#Getter
#Setter
#Entity
#Table(name = "crypt_test_table")
#IdClass(value = SqlFunctionTest.class) public class SqlFunctionTest implements Serializable {
#Id
private Long id;
#Column(name = "name")
#ColumnTransformer(
forColumn = "name",
read = "CONVERT(AES_DECRYPT(name, get_enc_key() ,get_aes_init_vector()) USING utf8)",
write = "AES_ENCRYPT(?, get_enc_key(), get_aes_init_vector())"
)
private String name;
}
I m trying to insert and select by encrypt and decrypt which I declared on my entity.
when I read it, it worked. like this.
SELECT
SQLFUNCTIO0_.ID AS ID1_13_,
SQLFUNCTIO0_.NAME AS NAME2_13_
FROM
CRYPT_TEST_TABLE SQLFUNCTIO0_
WHERE
CONVERT(AES_DECRYPT(SQLFUNCTIO0_.NAME, GET_ENC_KEY() ,GET_AES_INIT_VECTOR()) USING UTF8)='TROY.T'
but when i save an entity, it doesn't work like this.
INSERT
INTO
CRYPT_TEST_TABLE
(ID, NAME)
VALUES
(NULL, 'TROY.T')
This is the test code I did.
#Test
public void testSave(){
System.out.println("JPA TEST");
SqlFunctionTest entity = new SqlFunctionTest();
entity.setName("troy.t");
jpaCryptoService.save(entity);
}
#Test
public void testSelect(){
List<SqlFunctionTest> op = jpaCryptoService.findByName("troy.t");
System.out.println("op = " + op);
}
What's wrong with me?
2022-07-11T10:27:02.091+09:00 INFO 25748 --- [kground-preinit] o.h.v.i.u.Version : HV000001: Hibernate Validator 6.2.3.Final
2022-07-11T10:27:02.126+09:00 INFO 25748 --- [ main] ApplicationTest : Starting ApplicationTest using Java 11.0.14.1 on TroyTui-MacBookPro.local with PID 25748
2022-07-11T10:27:03.188+09:00 INFO 25748 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-07-11T10:27:03.592+09:00 INFO 25748 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 399 ms. Found 122 JPA repository interfaces.
2022-07-11T10:27:04.501+09:00 INFO 25748 --- [ main] c.z.h.HikariDataSource : HikariPool-1 - Starting...
2022-07-11T10:27:04.751+09:00 INFO 25748 --- [ main] c.z.h.HikariDataSource : HikariPool-1 - Start completed.
2022-07-11T10:27:04.829+09:00 INFO 25748 --- [ main] o.h.j.i.u.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-07-11T10:27:04.867+09:00 INFO 25748 --- [ main] o.h.Version : HHH000412: Hibernate ORM core version 5.6.9.Final
2022-07-11T10:27:04.996+09:00 INFO 25748 --- [ main] o.h.a.c.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-07-11T10:27:05.073+09:00 INFO 25748 --- [ main] o.h.d.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2022-07-11T10:27:05.564+09:00 WARN 25748 --- [ main] o.h.m.RootClass : HHH000038: Composite-id class does not override equals(): com.dktechin.saas.smartfactory.test.SqlFunctionTest
2022-07-11T10:27:05.564+09:00 WARN 25748 --- [ main] o.h.m.RootClass : HHH000039: Composite-id class does not override hashCode(): com.dktechin.saas.smartfactory.test.SqlFunctionTest
2022-07-11T10:27:06.228+09:00 INFO 25748 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-07-11T10:27:06.233+09:00 INFO 25748 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-07-11T10:27:10.167+09:00 INFO 25748 --- [ main] o.e.j.u.log : Logging initialized #9863ms to org.eclipse.jetty.util.log.Slf4jLog
2022-07-11T10:27:11.211+09:00 INFO 25748 --- [ main] ApplicationTest : Started ApplicationTest in 9.59 seconds (JVM running for 10.908)
JPA TEST
2022-07-11T10:27:11.393+09:00 INFO 25748 --- [ main] p6spy :
SELECT
SQLFUNCTIO0_.ID AS ID1_13_0_,
SQLFUNCTIO0_.NAME AS NAME2_13_0_
FROM
CRYPT_TEST_TABLE SQLFUNCTIO0_
WHERE
SQLFUNCTIO0_.ID=NULL
AND SQLFUNCTIO0_.NAME='TROY.T'
Connection ID: 2
Execution Time: 24 ms
Call Stack (number 1 is entry point):
----------------------------------------------------------------------------------------------------
2022-07-11T10:27:11.443+09:00 INFO 25748 --- [ main] p6spy :
INSERT
INTO
CRYPT_TEST_TABLE
(ID, NAME)
VALUES
(NULL, 'TROY.T')
Connection ID: 2
Execution Time: 14 ms
Call Stack (number 1 is entry point):
----------------------------------------------------------------------------------------------------
2022-07-11T10:27:11.602+09:00 INFO 25748 --- [ main] p6spy :
SELECT
SQLFUNCTIO0_.ID AS ID1_13_,
SQLFUNCTIO0_.NAME AS NAME2_13_
FROM
CRYPT_TEST_TABLE SQLFUNCTIO0_
WHERE
CONVERT(AES_DECRYPT(SQLFUNCTIO0_.NAME, GET_ENC_KEY() ,GET_AES_INIT_VECTOR()) USING UTF8)='TROY.T'
Connection ID: 3
Execution Time: 14 ms
Call Stack (number 1 is entry point):
----------------------------------------------------------------------------------------------------
op = []

Postman - 401 unauthorized status | Spring Boot

I prepared very simple REST APi.
I am trying to do requests with postman but i get 401 Unauthorized. No matter what kind request it is. I have Windows 11 system, Java 11, Postman Version 9.8.2
Postman:
application.properties file:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/students
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
Spring Application:
#SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
public class StudentsmanagerApplication {
public static void main(String[] args) {
SpringApplication.run(StudentsmanagerApplication.class, args);
}
Controller class:
#RestController
#RequestMapping("/student")
public class StudentController {
private StudentService studentService;
#GetMapping
public ResponseEntity<List<Student>> getAllStudents() {
List<Student> students = studentService.findAllStudent();
return new ResponseEntity<>(students, HttpStatus.OK);
}
#GetMapping("find/{id}")
public ResponseEntity<Student> getAllStudentsById(#PathVariable Long id) {
Student student = studentService.findStudentById(id);
return new ResponseEntity<>(student, HttpStatus.OK);
}
#PostMapping
public ResponseEntity<Student> addEmployee(#RequestBody Student student) {
Student newStudent = studentService.addStudent(student);
return new ResponseEntity<>(newStudent, HttpStatus.CREATED);
}
#PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(#PathVariable Long id, #RequestBody Student
student) {
Student updatedStudent = studentService.updateStudent(id, student);
return new ResponseEntity<>(updatedStudent, HttpStatus.UPGRADE_REQUIRED);
}
#DeleteMapping("/{id}")
public ResponseEntity<?> deleteStudent(#PathVariable Long id) {
studentService.deleteStudent(id);
return new ResponseEntity<>(HttpStatus.OK);
}
Service class:
#Service
public class StudentService {
private StudentRepository studentRepository;
public Student addStudent(Student student) {
student.setStudentCode(UUID.randomUUID().toString());
return studentRepository.save(student);
}
public List<Student> findAllStudent() {
return studentRepository.findAll();
}
public Student updateStudent(Long id, Student student) {
Student studentById = studentRepository
.findById(id).orElseThrow(() -> new StudentNotFoundException("Student by id
" + " doesn't Exist"));
studentById.setName(student.getName());
studentById.setLastName(student.getLastName());
studentById.setEmail(student.getEmail());
studentById.setPhone(student.getPhone());
return studentRepository.save(studentById);
}
public Student findStudentById(Long id) {
return studentRepository
.findById(id).orElseThrow(() -> new StudentNotFoundException("Student
doesn't exist "));
}
public void deleteStudent(Long id) {
studentRepository.deleteById(id);
}
Spring logs:
2022-01-08 10:53:19.661 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : Starting StudentsmanagerApplication using Java 11.0.13 on LAPTOP-9F9MO24J with PID 20120 (C:\Users\mkord\IdeaProjects\studentsmanager\target\classes started by mkord in C:\Users\mkord\IdeaProjects\studentsmanager)
2022-01-08 10:53:19.661 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : No active profile set, falling back to default profiles: default
2022-01-08 10:53:20.539 INFO 20120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-01-08 10:53:20.596 INFO 20120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 50 ms. Found 1 JPA repository interfaces.
2022-01-08 10:53:21.262 INFO 20120 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-01-08 10:53:21.278 INFO 20120 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-08 10:53:21.278 INFO 20120 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-08 10:53:21.422 INFO 20120 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-01-08 10:53:21.422 INFO 20120 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1684 ms
2022-01-08 10:53:21.662 INFO 20120 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-01-08 10:53:21.703 INFO 20120 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.3.Final
2022-01-08 10:53:21.856 INFO 20120 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-01-08 10:53:21.976 INFO 20120 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-08 10:53:22.336 INFO 20120 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-01-08 10:53:22.352 INFO 20120 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2022-01-08 10:53:22.968 INFO 20120 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-01-08 10:53:22.984 INFO 20120 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-01-08 10:53:23.032 WARN 20120 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-01-08 10:53:23.824 INFO 20120 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#36931450, org.springframework.security.web.context.SecurityContextPersistenceFilter#451a4187, org.springframework.security.web.header.HeaderWriterFilter#6db04a6, org.springframework.security.web.csrf.CsrfFilter#630c3af3, org.springframework.security.web.authentication.logout.LogoutFilter#4866e0a7, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#66d44581, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#4ac0d49, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#74919649, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#2ea4e762, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5c215642, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#1317ac2c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#7d07e04e, org.springframework.security.web.session.SessionManagementFilter#426913c4, org.springframework.security.web.access.ExceptionTranslationFilter#38197e82, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#5a07ae2f]
2022-01-08 10:53:23.914 INFO 20120 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-08 10:53:23.930 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : Started StudentsmanagerApplication in 4.851 seconds (JVM running for 6.309)
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
2022-01-08 10:59:13.941 WARN 20120 --- [nio-8080-exec-2] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [184] milliseconds.
Thank You in advance for any suggestion

Spring boot server all shutdown at the same time for unknown reason

We have a bunch of spring boot servers and they are different code base (but all cloned from the same base)
They all went down last night, at slightly different time. When I looked at the log, it didn't say much. Here is the log
2021-08-06 06:22:09.735 INFO 1 --- [ Thread-4] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'threadPoolTaskScheduler'
2021-08-06 06:22:09.747 INFO 1 --- [ Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-08-06 06:22:09.750 INFO 1 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-08-06 06:22:09.761 INFO 1 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Here is the log from another project we have
2021-08-06 06:36:39.317 INFO 1 --- [ Thread-3] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
2021-08-06 06:36:39.324 INFO 1 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2021-08-06 06:36:39.329 INFO 1 --- [ Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-08-06 06:36:39.341 INFO 1 --- [ Thread-3] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-08-06 06:36:39.354 INFO 1 --- [ Thread-3] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
What could be the reason and how do I troubleshoot this?
The springboot runs inside a docker image, running on ubuntu.
The servers were able to be rebooted immediately without issue.

Hibernate Validation does not look up error messages in a Spring boot application

This is my Spring boot project set up.
I have a standard Spring boot JPA stack in which I am trying to validate the state of the instance variables. My bean is as follows:
Configuration
#Component
public class ConfigurationHelper {
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public Validator validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setValidationMessageSource(this.messageSource());
return factoryBean;
}
}
Model class
#Table(name = "user_station", indexes = {
#Index(columnList = "station_id", name = "station_index_station_id"),
#Index(columnList = "station_name", name="station_index_name"),
#Index(columnList = "hd_enabled", name = "station_index_hd_enabled")
})
#Entity
#EqualsAndHashCode(exclude = {"createdTimeStamp", "updatedTimestamp"}, callSuper = true)
#ToString(exclude = {"createdTimeStamp", "updatedTimestamp"}, callSuper = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Station extends IError {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#JsonIgnore
private Long id;
// Represents a station id for the user.
#Column(name="station_id", nullable = false, unique = true)
#NotEmpty(message = "{station.id.empty}")
#Pattern(regexp = "^K|W[A-Za-z0-9\\-].*$", message = "{station.id.name.not.valid}")
private String stationId;
#Column(name="station_name", nullable = false)
#JsonProperty("name")
#NotEmpty(message = "{station.name.empty}")
private String stationName;
#Column(name = "hd_enabled")
private Boolean hdEnabled;
#Column(name="call_sign", nullable = false)
#NotEmpty(message = "{station.call.sign.empty}")
private String callSign;
#Column(name="user_created_timestamp")
#JsonIgnore
private LocalDateTime createdTimeStamp;
#Column(name="user_modified_timestamp")
#JsonIgnore
private LocalDateTime updatedTimestamp;
/**
* Initialises the timestamps prior to update or insertions.
*
* <p>The implementation ensures that time stamps would always reflect the time when entities
* were persisted or updated.
*/
#PrePersist
#PreUpdate
public void setTimestamps() {
LocalDateTime utcNow = LocalDateTime.now(ZoneOffset.UTC);
if (this.createdTimeStamp == null) {
this.createdTimeStamp = utcNow;
}
this.updatedTimestamp = utcNow;
if (this.hdEnabled == null) {
this.hdEnabled = Boolean.FALSE;
}
}
// Getters, Setters, Equals and HashCode functions.
}
Unit tests
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes= {App.class})
public class StationTest {
#Autowired
private Validator validator;
private Station station;
#Before
public void setUp() throws Exception {
this.station = new Station();
}
#Test
public void testValidator_allNulls() {
Set<ConstraintViolation<Station>> constraintViolations =
this.validator.validate(this.station);
MatcherAssert.assertThat(constraintViolations.isEmpty(), Is.is(false));
for (ConstraintViolation<Station> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getMessage());
}
}
}
This is my output
. . . . Rest of the stack trace omitted . . . .
2018-12-01 23:30:38.532 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : Starting StationTest on Kartiks-MacBook-Pro-2.local with PID 21297 (started by krishnanand in /Users/krishnanand/projects/iheartmedia)
2018-12-01 23:30:38.533 DEBUG 21297 --- [ main] com.iheartmedia.model.StationTest : Running with Spring Boot v2.0.5.RELEASE, Spring v5.0.9.RELEASE
2018-12-01 23:30:38.539 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : No active profile set, falling back to default profiles: default
2018-12-01 23:30:38.596 INFO 21297 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 23:30:38 PST 2018]; root of context hierarchy
2018-12-01 23:30:39.565 INFO 21297 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b7d31eab] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-12-01 23:30:39.730 INFO 21297 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-12-01 23:30:39.871 INFO 21297 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-12-01 23:30:39.903 INFO 21297 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-12-01 23:30:39.917 INFO 21297 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-12-01 23:30:40.030 INFO 21297 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2018-12-01 23:30:40.031 INFO 21297 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-12-01 23:30:40.066 INFO 21297 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-12-01 23:30:40.196 INFO 21297 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-12-01 23:30:40.652 INFO 21297 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-12-01 23:30:40.985 INFO 21297 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2018-12-01 23:30:41.351 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.586 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 23:30:38 PST 2018]; root of context hierarchy
2018-12-01 23:30:41.624 WARN 21297 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-12-01 23:30:41.658 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/stations],methods=[GET]}" onto public java.util.List<com.iheartmedia.model.Station> com.iheartmedia.controller.StationController.retrieveAllStations()
2018-12-01 23:30:41.660 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/station],methods=[POST]}" onto public org.springframework.http.ResponseEntity<com.iheartmedia.dto.StationMixin> com.iheartmedia.controller.StationController.createStation(com.iheartmedia.model.Station,org.springframework.validation.Errors)
2018-12-01 23:30:41.660 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/station],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<com.iheartmedia.dto.StationMixin> com.iheartmedia.controller.StationController.deleteStation(com.iheartmedia.model.Station)
2018-12-01 23:30:41.663 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-12-01 23:30:41.664 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-12-01 23:30:41.687 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.687 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.979 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : Started StationTest in 3.704 seconds (JVM running for 4.431)
{station.call.sign.empty}
{station.name.empty}
{station.id.empty}
2018-12-01 22:11:10.360 INFO 18663 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 22:11:06 PST 2018]; root of context hierarchy
2018-12-01 22:11:10.363 INFO 18663 --- [ Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-12-01 22:11:10.364 INFO 18663 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-12-01 22:11:10.367 INFO 18663 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
messages.properties Resource bundle
station.not.found=Station {0} was not found
station.id.empty=Station ID can not be empty.
station.id.format.not.valid=Station ID ${validatedValue} is not valid. Station ID should start with either W or K.
station.name.empty=Station name can not be empty.
station.call.sign.empty=Station call sign can not be empty.
Our dependency tree
I have read the following
Custom error messaging on Hibernate Validation
Custom Message Key in Hibernate validator not working with message.property
Does Spring Boot automatically resolve message keys in javax and hibernate validation annotations
but I can not still figure out what I am doing wrong.
UPDATE
Upon #Jonathan Johx's suggestion, I changed the basename of the ResourceBundleMessage to messages (Updated the code snippet as well), but I still get the error.
The issue is because the classpath: does reference to root of folder which is ConfigurationHelper class, it's not found. Try to rename file name to ValidationMessages.properties which is used by Validator and update the following line:
messageSource.setBasenames("ValidationMessages");
UPDATED
If you want to use validation messages by default then you have to create a file called:
ValidationMessages.properties
And add properties that you consider necessary.

Spring boot stops as I write some JPA queries in the repository

I am using spring boot with H2 database. My application stops with below text on console.
2016-08-01 10:36:08.610 INFO 3920 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-08-01 10:36:08.651 INFO 3920 --- [ost-startStop-1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.11.Final}
2016-08-01 10:36:08.651 INFO 3920 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-08-01 10:36:08.651 INFO 3920 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-08-01 10:36:08.801 INFO 3920 --- [ost-startStop-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-08-01 10:36:09.031 INFO 3920 --- [ost-startStop-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2016-08-01 10:36:09.131 INFO 3920 --- [ost-startStop-1] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-08-01 10:36:09.291 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2016-08-01 10:36:09.291 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000102: Fetching database metadata
2016-08-01 10:36:09.301 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000396: Updating schema
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000261: Table found: TEST.PUBLIC.EMAILDATA
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000037: Columns: [quantity, emailto, id, autostart, emailfrom]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000108: Foreign keys: []
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000126: Indexes: [primary_key_2]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000261: Table found: TEST.PUBLIC.STATUS
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000037: Columns: [exchangefile, consolidate, processdate, aggregateall, scriptmaster, sendmail, id, insiderstrade]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000108: Foreign keys: []
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000126: Indexes: [primary_key_9]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000232: Schema update complete
My repository is:
#Transactional
public interface EmailDataRepository extends JpaRepository<EmailData,Long>{
#Query("SELECT p FROM EmailData P")
public EmailData findLastRow();
}
And DBConfig is:
#Configuration
#EnableTransactionManagement
#ComponentScan("com.demo.*")
#PropertySource("classpath:application.properties")
#EntityScan(basePackages = {"com.demo.model"})
#EnableJpaRepositories("com.demo.repository.main")
public class DBConfig {....}
Model:
#Entity
#Table(name="EmailData")
public class EmailData {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
private String emailTo;
private String emailFrom;
private String quantity;
private Boolean autoStart;
...}
Your H2 database url should have the following configuration
DB_CLOSE_ON_EXIT=FALSE
Spring Boot documentation has a quote:
If, for whatever reason, you do configure the connection URL for an embedded database, care should be taken to ensure that the database’s automatic shutdown is disabled. If you’re using H2 you should use DB_CLOSE_ON_EXIT=FALSE to do so. If you’re using HSQLDB, you should ensure that shutdown=true is not used. Disabling the database’s automatic shutdown allows Spring Boot to control when the database is closed, thereby ensuring that it happens once access to the database is no longer needed.

Resources