如何查询基于Java Hibernate与Angular的Web服务中H2数据库的大小?
Got it, let's break down the practical ways you can check the size of your file-based H2 database—since you mentioned finding H2 files, these methods will fit your setup perfectly:
1. Use H2's Built-in SQL Queries
This is the most straightforward approach if you can run SQL against your database (via H2 console, your app's query layer, or a database tool):
- To get the size of the main persistent data file (in bytes):
Convert the result to KB/MB by dividing bySELECT FILE_SIZE() FROM INFORMATION_SCHEMA.SYSTEM_USERS;1024or1024*1024respectively. - For a total of all associated files (data file, transaction logs, etc.), use:
This sums up the size of every file linked to your H2 database instance.SELECT SUM(FILE_LENGTH) AS TOTAL_DB_SIZE_BYTES FROM INFORMATION_SCHEMA.FILES;
2. Check the File System Directly
H2 file-based databases create several files in the directory specified in your Hibernate JDBC URL (look for the path starting with jdbc:h2:file:/). Key files include:
your-db-name.mv.db: The main data file (largest one)your-db-name.trace.db: Transaction/log fileyour-db-name.lock.db: Small lock file (negligible size)
Calculate their total size directly on your system:- On Windows: Select the files, right-click → "Properties" to see total size
- On macOS/Linux: Run
du -sh /path/to/your/db-directory/in the terminal to get the directory's total size
3. Fetch Size Programmatically via Hibernate/JPA
If you need to get the database size directly in your Java code, execute the SQL queries above using Hibernate Session or JPA EntityManager:
Using Hibernate Session:
try (Session session = sessionFactory.openSession()) { Long fileSizeBytes = (Long) session.createNativeQuery("SELECT FILE_SIZE()").uniqueResult(); double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0); System.out.println("Database size: " + fileSizeMB + " MB"); }
Using JPA EntityManager:
try (EntityManager em = entityManagerFactory.createEntityManager()) { Long totalSizeBytes = (Long) em.createNativeQuery("SELECT SUM(FILE_LENGTH) FROM INFORMATION_SCHEMA.FILES") .getSingleResult(); double totalSizeMB = totalSizeBytes / (1024.0 * 1024.0); System.out.println("Total database size (all files): " + totalSizeMB + " MB"); }
4. Use the H2 Console
If you have the H2 console enabled (common in dev setups):
- Launch it (usually at
http://localhost:8082if running with your app) - Connect using your database's JDBC URL, username, and password
- Run one of the SQL queries from method 1—you'll see the size result right away.
Quick note: If you were using an in-memory H2 instance (jdbc:h2:mem:), there are no persistent files, so FILE_SIZE() would return 0. But since you found H2 files, this doesn't apply to your case.
内容的提问来源于stack exchange,提问作者user12465043

