I was addicted to Spring Data JDBC, which I was reviewing somehow, so I made a note. (Although the base Spring boot is a little old ...)
I just tried to insert an object (insert a record) in a table with Spring Data JDBC
Apparently, Spring Data JDBC issues SQL when the field with @ID is an object type, Insert when it is null, and update when it is not null. The PK of the table must be Auto Generated.
reference https://stackoverflow.com/questions/50371775/why-does-spring-data-jdbc-not-save-my-car-object
object
Users.java
public class Users {
@Id
private Integer user_id;
private String password;
private String notes;
service
SampleService.java
@Transactional
@Service
public class SampleService {
@Autowired
private UserRepository dao;
//Abbreviation
//It's a very crude code, but ...
public void add(Integer id) {
LocalDateTime time = LocalDateTime.now();
Users user = new Users(id, "password", time.toString());
logger.info(user.toString());
Users inserted = dao.save(user);
}
For test execution
SampleServiceTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleServiceTest {
@Autowired
private SampleService service;
//Update when you run this
@Test
public void test1() {
service.add(3);
}
//When you execute this, Insert
@Test
public void test2() {
service.add(null);
}
}
test1 () runtime
2019-11-19 18:41:47.275 INFO 37316 --- [ main] org.example.test.service.SampleService : userid: 3, note: 2019-11-19T18:41:47.274
Postgre SQL trace at that time
2019-11-19 09:41:47.326 UTC [167] LOG: execute <unnamed>: BEGIN
2019-11-19 09:41:47.334 UTC [167] LOG: execute <unnamed>: UPDATE users SET user_id = $1, password = $2, notes = $3 WHERE user_id = $4
2019-11-19 09:41:47.334 UTC [167] DETAIL: parameters: $1 = '3', $2 = 'password', $3 = '2019-11-19T18:41:47.274', $4 = '3'
test2 () runtime
2019-11-19 18:41:47.355 INFO 37316 --- [ main] org.example.test.service.SampleService : userid: null, note: 2019-11-19T18:41:47.355
Postgre SQL trace at that time
2019-11-19 09:41:47.368 UTC [167] LOG: execute <unnamed>: BEGIN
2019-11-19 09:41:47.368 UTC [167] LOG: execute <unnamed>: INSERT INTO users (password, notes) VALUES ($1, $2)
RETURNING *
2019-11-19 09:41:47.368 UTC [167] DETAIL: parameters: $1 = 'password', $2 = '2019-11-19T18:41:47.355'
For the time being, let's change the DDL and raise the version of Spring boot. With Postgres 10, you can make it Auto Generated. https://qiita.com/nuko_yokohama/items/7d0d5525bcefaa3332ce
Oh, I referred to here for the SQL trace settings of PostgreSQL. https://www.kakiro-web.com/postgresql/postgresql-sql-log-system.html
Recommended Posts