forked from solid-connection/solid-connect-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseCleaner.java
More file actions
49 lines (40 loc) · 1.51 KB
/
DatabaseCleaner.java
File metadata and controls
49 lines (40 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.example.solidconnection.support;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
@Component
public class DatabaseCleaner {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@PersistenceContext
private EntityManager em;
@Transactional
public void clear() {
em.clear();
truncate();
Objects.requireNonNull(redisTemplate.getConnectionFactory())
.getConnection()
.serverCommands()
.flushDb();
}
private void truncate() {
em.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0").executeUpdate();
getTruncateQueries().forEach(query -> em.createNativeQuery(query).executeUpdate());
em.createNativeQuery("SET FOREIGN_KEY_CHECKS = 1").executeUpdate();
}
@SuppressWarnings("unchecked")
private List<String> getTruncateQueries() {
String sql = """
SELECT CONCAT('TRUNCATE TABLE ', TABLE_NAME, ';') AS q
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = (SELECT DATABASE())
AND TABLE_TYPE = 'BASE TABLE'
""";
return em.createNativeQuery(sql).getResultList();
}
}