I'm trying to use mybatis-guice with mysql but I keep catching the next exception:
Error querying database. Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
Here is the code I try to run:
public class DaoImpl implements Dao {
#Inject
private MyMapper mapper;
public String getSomething() {
return mapper.getSomething();
}
}
public interface Dao {
String getSomething();
}
public interface MyMapper {
#Select("SELECT DATE_FORMAT(NOW(),'%d/%m/%Y %H:%i') as time")
String getSomething();
}
Injector injector = Guice.createInjector(
new MyBatisModule() {
#Override
protected void initialize() {
install(JdbcHelper.MySQL);
environmentId("development");
bindDataSourceProviderType(PooledDataSourceProvider.class);
bindTransactionFactoryType(JdbcTransactionFactory.class);
addMapperClass(MyMapper.class);
bindProperties(binder(), getMybatisProperties());
bind(Dao.class).to(DaoImpl.class);
}
}
);
private Properties getMybatisProperties() {
Properties myBatisProperties = new Properties();
myBatisProperties.setProperty("JDBC.host", "127.0.0.1");
myBatisProperties.setProperty("JDBC.port", "3306");
myBatisProperties.setProperty("JDBC.schema", "my_schema");
myBatisProperties.setProperty("JDBC.driver", "com.mysql.jdbc.Driver"));
myBatisProperties.setProperty("JDBC.username", "root");
myBatisProperties.setProperty("JDBC.password", "");
myBatisProperties.setProperty("JDBC.autoCommit", "false");
return myBatisProperties;
}
And than I try to run:
injector.getInstance(Dao.class).getSomething()
I tried to remove myBatisProperties.setProperty("JDBC.driver", "com.mysql.jdbc.Driver")); but the result was the same.
Also, after several hours of debugging the code, install(JdbcHelper.MySQL); should add the driver by itself. Is this assumption correct?
The exception is thrown on mapper.getSomething();
Ideas???
You need a driver mysql-connector-java or verify the version of the driver and your put mysql-connector-java-bin.jar in the lib
Related
I have the below configuration class definition in java springboot. However, it fails for reference to property values.
#org.springframework.context.annotation.Configuration
public class HbaseConfig {
#Value("${keytab.user.name}")
private String username;
#Value("${keytab.path}")
private String keytabpath;
#Bean
public Connection getHbaseConnect() throws IOException {
Configuration conf = HBaseConfiguration.create();
Connection connection = ConnectionFactory.createConnection(conf);
UserGroupInformation.setConfiguration(conf);
System.out.println("hbase connect..is connection closed..." + connection.isClosed());
UserGroupInformation.loginUserFromKeytabAndReturnUGI(username, keytabpath);
return connection;
}
#Bean
public Admin getHbaseAdmin(Connection connection) throws IOException{
Admin admin = connection.getAdmin();
return admin;
}
}
application.properties
keytab.user.name="username"
keytab.path="pathtokeytab"
To put it simple, I need the above keytab username and path read from a property file in my HbaseConfig class.
Can you please try out the below method,
#ConfigurationProperties(prefix = "keytab")
public class KeyTabConfig {
private String username;
private String path;
public String getUsername(){ return this.username; }
public String getPath(){ return this.path;}
}
Habseconfig class as follows
#Configuration
#EnableConfigurationProperties({ KeyTabConfig.class})
public class HbaseConfig {
#Bean
public Connection getHbaseConnect(KeyTabConfig keyTabConfig) throws IOException {
Configuration conf = HBaseConfiguration.create();
Connection connection =
ConnectionFactory.createConnection(conf);
UserGroupInformation.setConfiguration(conf);
System.out.println("hbase connect..is connection closed..." +
connection.isClosed());
UserGroupInformation.loginUserFromKeytabAndReturnUGI(keyTabConfig.getUsername(), keyTabConfig.getPath());
return connection;
}
#Bean
public Admin getHbaseAdmin(Connection connection) throws IOException{
Admin admin = connection.getAdmin();
return admin;
}
}
application.properties file as
keytab.username=uname
keytab.path=path
Make sure your property file name should application.properties and location should in
src/main/resources/application.properties
used only #Configuration at the class level and also use #PropertySource to define the location of our properties file.#PropertySource("classpath:configprops.properties") if your property file name is different.
Otherwise, Spring uses the default location (classpath:application.properties).
The actual processing of #Value annotation is performed by BeanPostProcessor and so we cannot use #Value within BeanPostProcessor types.
Examples: https://www.concretepage.com/spring-5/spring-value#placeholder
Link: How exactly does the Spring BeanPostProcessor work?
HikariCP Github page have the following code:
props.put("dataSource.logWriter", new PrintWriter(System.out));
But I'm getting NullPointerException beacuse LogWriter isn't supported,
DriverDataSource final HikariCP class:
#Override
public PrintWriter getLogWriter() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
#Override
public void setLogWriter(PrintWriter logWriter) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
Is this solution for updating HikariCP logging is irrelevant?
I didn't get any answer in group
EDIT
Hikari initialization code uses PoolBase which is initializing datasource with DriverDataSource (which doesn't support logWriter):
else if (jdbcUrl != null && ds == null) {
ds = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password);
I must send jdbcUrl in Oracle and I failed setDataSourceClassName in conjunction with setDriverClassName
this is my configuration:
#Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
.setCredentials("neo4j", "neo4j")
.setURI("http://localhost:7474");
return config;
}
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory(getConfiguration(), "movies.spring.data.neo4j.domain");
}
#Bean
#Override
// #Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return getSessionFactory().openSession();
}
everytime i want to get the result from neo4j and it hits me a nullPointerError as shown:
Exception in thread "main" java.lang.NullPointerException
at org.neo4j.ogm.context.RestModelMapper.mapEntity(RestModelMapper.java:153)
at org.neo4j.ogm.context.RestModelMapper.map(RestModelMapper.java:76)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:94)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:73)
at org.neo4j.ogm.session.Neo4jSession.query(Neo4jSession.java:313)
at movies.spring.data.neo4j.controllers.BenchmarkDeleteController.run(BenchmarkDeleteController.java:57)
where the specified line 57 is:
Result results = neoSession.query("MATCH (n:USER) WHERE n.isBanned={param} RETURN n as user",
Collections.<String, Object>singletonMap("param", 1));
I wonder what could be the problem? I made sure that the session isnt null.
If you do not have a node entity that the results can be mapped to, the RestModelMapper throws a NullPointerException in Neo4j-OGM 2.0.1 (which SDN 4.1.1 depends on). This was fixed in Neo4j OGM 2.0.2- https://github.com/neo4j/neo4j-ogm/issues/150
Please check that the nodes returned can be mapped to node entities (their labels should match) and then override the neo4j-ogm-code and driver dependencies to use 2.0.2.
I am having the following issue: when I am connecting to db using MyBatis I get an NPE.
Here is the class for setting connection:
public class SetDBConnection {
private Mapper mapper;
private SqlSession session;
private Configuration configuration;
public SetDBConnection() {
configuration = new Configuration();
configuration.setJdbcTypeForNull(JdbcType.VARCHAR);
configuration.setLogImpl(Slf4jImpl.class);
configuration.setDefaultExecutorType(ExecutorType.REUSE);
configuration.addMapper(Mapper.class);
Properties properties = null;
try {
properties = readProperties();
} catch (IOException e) {
e.printStackTrace();
}
configuration.setVariables(properties);
}
public Mapper openSession() {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
session = sqlSessionFactory.openSession();
mapper = session.getMapper(Mapper.class);
return mapper;
}
public void closeSession() {
session.commit();
session.close();
}
private Properties readProperties() throws IOException {
Properties properties = new Properties();
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("connection.properties");
if (inputStream != null) {
properties.load(inputStream);
} else {
throw new FileNotFoundException("property file not found in the classpath");
}
inputStream.close();
return properties;
}
}
And here I call it and try to Insert data
SetDBConnection conn = new SetDBConnection();
Person p = new Person();
p.setName("Alex");
p.setLastName("Bondar");
p.setTelephone("+79267157256");
p.setPersonalId("777-216");
Mapper mapper=conn.openSession();
try {
System.out.println("All set to go");
mapper.saveOrUpdatePerson(p);
} finally {
conn.closeSession();
}
Stacktrace is the following:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error opening session. Cause: java.lang.NullPointerException
### The error may exist in org/abondar/experimental/mybatisdemo/mappers/Mapper.java (best guess)
### Cause: java.lang.NullPointerException
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:100)
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession(DefaultSqlSessionFactory.java:47)
at org.abondar.experimental.mybatisdemo.SetDBConnection.openSession(SetDBConnection.java:51)
at org.abondar.experimental.mybatisdemo.Main.main(Main.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:95)
... 8 more
What can be wrong and is there any way not to re-establish DB-connection for every action(select,insert or delete)?
It seems you have no Environment and TransactionFactory defined. According to the docs you should initialize MyBatis somehow like this:
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
Thanks Frank for DataSource idea. I used default pooled dataSource and this problem looks to be solved
Spring Boot 1.1.5.RELEASE
public class DataAccessTests
{
private EmbeddedDatabase db;
#Before
public void setUp()
{
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
db = builder.setType(H2).addDefaultScripts().build();
}
#Test
public void testDataAccess() {
JdbcTemplate template = new JdbcTemplate(db);
int r = template.queryForObject("select 1", Integer.class);
assertEquals(r, 1);
}
#After
public void tearDown() {
db.shutdown();
}
}
Exception
org.h2.jdbc.JdbcSQLException: Wrong user name or password [28000-181]
Where I make a mistake?
I'm sorry for my mistake. When I wrote a demo application for this error I found a solution.
The problem was that the settings were taken from my application rather than the default.
After I commented out#SpringApplicationConfiguration(classes = App.class) everything works fine.