0

I am trying to setup SQLITE as an in-memory database in my spring-boot application. But when i try to query the database then it gives me an error "No such table"

Can someone please recommend what am i doing wrong? I need to have SQLITE as a in memory only and we only use jdbc in our project.

Here is my code:

application.properties

spring.datasource.url=jdbc:sqlite:memory
spring.datasource.username=
spring.datasource.password= 

spring.datasource.platform=sqlite
spring.datasource.driver-class-name=org.sqlite.JDBC

MyRepo.java

@Repository
public class MyRepo{

    @Autowired
    private NamedParameterJdbcTemplate namedJdbc;
    
    
    public String getUserName() throws Exception{
        String userName = null;
        String sql = "SELECT username FROM emp WHERE username=:name";
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        paramSource.addValue("name", "tuser");
        userName = this.namedJdbc.query(sql, paramSource, (rs) -> {
                String name = null;
                while (rs.next()) {
                    name = rs.getString("username").trim();
                    return name;
                }
                return null;
            });
        
        return userName;
    }
}

UserDaoTest.java

@SpringBootTest
public class UserDaoTest {
    
    @Autowired
    private MyRepo rep;

    
    @Test
    public void testFindByname() throws Exception{
        rep.getUserName();
        
    }

}

I also have schema.sql and data.sql files under src/main/resources

schema.sql

DROP TABLE IF EXISTS emp;CREATE TABLE IF NOT EXISTS emp(username VARCHAR(20), empId BIGINT, PRIMARY KEY(empId) )

data.sql

INSERT INTO emp(username,empId) VALUES ('tuser',1001);

Exception that i am getting:

PreparedStatementCallback; uncategorized SQLException for SQL [SELECT username FROM Chats WHERE username=?]; SQL state [null]; error code [1]; [SQLITE_ERROR] SQL error or missing database (no such table: Chats)
user1945064
  • 199
  • 3
  • 4
  • 18

2 Answers2

0

well, I am shooting in the dark but looks like you need to add the schema for 'Chats' table as well to your schema.sql

Suhel Khan
  • 55
  • 2
  • 7
0

https://sqlite.org/inmemorydb.html

The database ceases to exist as soon as the database connection is closed. Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases.

Your issue might be with spring boot opening multiple connections due to its connection pool configuration. If you're using hikari connection pool (default in newer spring boot versions), try adding these properties

spring.datasource.hikari.maximum-pool-size=1
spring.datasource.hikari.max-lifetime=0
Coderino Javarino
  • 2,819
  • 4
  • 21
  • 43