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
Related
so i got a very strange error message. Im currently working on a java web project with maven and testing the project with Eclipse and Tomcat. So I imported all the neccessary dependencys (mongo java driver, mongodb driver, mongodb driver core, bson and javax.servlet api), or so i thought. But still i'm getting this error over and over again.
If I run the code as part of a main method it works just fine...so im in the dark what could have caused this problem.
this is my MongoDB connector,
public class Connector {
final String HOST = "localhost";
final int PORT = 27017;
final String DBNAME = "mitfahrapp";
public static Connector instance;
public MongoClient connection;
public MongoDatabase database;
public Connector(){
this.connection = new MongoClient(this.HOST, this.PORT);
this.database = connection.getDatabase(DBNAME);
}
public MongoClient getClient() {
return connection;
}
public static Connector createInstance() throws UnknownHostException {
if (Connector.instance == null) {
Connector.instance = new Connector();
}
return Connector.instance;
}
public MongoCollection<Document> getCollection(String name) {
return this.database.getCollection(name);
}
public void CloseMongo() {
connection.close();
}
}
and this is part of my LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connector c = Connector.createInstance();
MongoCollection<Document> collection = c.getCollection("users");
String username = request.getParameter("username");
String password = request.getParameter("password");
Bson filterUsername = Filters.eq("username", username);
Bson filterPwd = Filters.eq("password", password);
Bson bsonFilter = Filters.and(filterUsername, filterPwd);
FindIterable<Document> doc = collection.find(bsonFilter);
if (doc != null) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
Thanks for any answers in advance!
This means that the classes are not included in the jar, if you are using maven you should use the maven shade plugin to include those.
I am trying to Configure Oracle DataSource Using Commons DBCP but its throwing subject error
I am working on CentOS
private String driverClassName="oracle.jdbc.driver.OracleDriver" ;
private String url="jdbc:oracle:thin:#164.173.28.18:1521:XE";
private String userName="username";
private String password="password";
private static int MAX_ACTIVE= 10;
private BasicDataSource ds = null;
public void init() throws SQLException{
ds = new BasicDataSource();
ds.setDriverClassName(driverClassName);
ds.setPassword(password);
ds.setUsername(userName);
ds.setUrl(url);
ds.setMaxActive(MAX_ACTIVE);
//check connections
ds.getConnection();
}
public Connection getOracleConnection() throws SQLException{
return ds.getConnection();
}
How can I fix
DB.java:27: error: cannot find symbol
ds.setMaxActive(MAX_ACTIVE); ^
symbol: method setMaxActive(int)
location: variable ds of type BasicDataSource
1 error
obviously, your datasource class doesn't support maxactive.
you need check your library version.
I have created a cron job that start during application restart but when i tried to create db connection i am geeting null pointer exception. I am able to create and use db from other module using same configuration.
Below is my Application.conf
db.abc.driver=com.mysql.jdbc.Driver
db.abc.url="jdbc:mysql://localhost:3306/db_name?useSSL=false"
db.abc.username=root
db.abc.password=""
db.abc.autocommit=false
db.abc.isolation=READ_COMMITTED
And code that tried to access db is
public class SchduleJob extends AbstractModule{
#Override
protected void configure() {
bind(JobOne.class)
.to(JobOneImpl.class)
.asEagerSingleton();
} }
#ImplementedBy(JobOneImpl.class)
public interface JobOne {}
#Singleton
public class JobOneImpl implements JobOne {
final ActorSystem actorSystem = ActorSystem.create("name");
final ActorRef alertActor = actorSystem.actorOf(AlertActor.props);
public JobOneImpl() {
scheduleJobs();
}
private Cancellable scheduleJobs() {
return actorSystem.scheduler().schedule(
Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds
Duration.create(6, TimeUnit.MINUTES), //Frequency 30 minutes
alertActor,
"alert",
actorSystem.dispatcher(),
null
);
}
}
public class AlertActor extends UntypedActor{
public static Props props = Props.create(AlertActor.class);
final ActorSystem actorSystem = ActorSystem.create("name");
final ActorRef messageActor = actorSystem.actorOf(MessageActor.props());
#Override
public void onReceive(Object message) throws Exception {
if(message != null && message instanceof String) {
RequestDAO requestDAO = new RequestDAO();
try {
List<DBRow> rows = requestDAO.getAllRow();
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
}
public class RequestDAO {
public List<DBRow> getAllRow() throws Exception {
List<DBRow> rows = new ArrayList<DBRow>();
Connection connection = null;
try {
connection = DB.getDataSource("abc").getConnection();
connection.setAutoCommit(false);
} catch(Exception exception) {
exception.printStackTrace();
if(connection != null) {
connection.rollback();
} else {
System.out.println("in else***********");
}
return null;
} finally {
if(connection != null)
connection.close();
}
return schools;
}
When i am calling method getAllRow() of RequestDAO class it's throwing
java.lang.NullPointerException
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:235)
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:235)
at play.utils.InlineCache.fresh(InlineCache.scala:69)
at play.utils.InlineCache.apply(InlineCache.scala:55)
at play.api.db.DB$.db(DB.scala:22)
at play.api.db.DB$.getDataSource(DB.scala:41)
at play.api.db.DB.getDataSource(DB.scala)
at play.db.DB.getDataSource(DB.java:33)
But same code is working without cron job. What should i do to remove this error
Play uses the Typesafe config library for configuration.
I suspect your current working directory from the cron script isn't set, so it's probably not finding your application.conf (application.properties) file.
However, Config is nice in that it allows you to specify where to look for the file, either by its base name (to choose among .conf | .properties | .json extensions) or the filename including the extension on the java command line:
To specify the base name, use -Dconfig.resource=/path/to/application
To specify the full name, use -Dconfig.file=/path/to/application.properties
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
I encountered some errors connecting to Hibernate. This gives an error:
public static void makeReport(String type, Map<String, Object> param) throws JRException, IOException{
JasperPrint jasperPrint = null;
**Connection con = HibernateUtil.getSessionFactory().openSession().connection();**error here
String outputFileName = "Hóa đơn ";
JRAbstractExporter exporter = null;
if(type == "7" || type == "8" || type == "9"){
if(type==REPORT_BY_MONTH){
jasperPrint = JasperFillManager.fillReport("data\\Thống kê theo tháng.jasper", param, con);
outputFileName += "thống kê theo tháng " + param.get("#Month") + "-" + param.get("#Year") + ".xlsx";;
}
You can find the code project here.
I think you are trying to generated a JSper report for that you might need JDBC conventional Connection Object.
Are you trying to get JDBC Connection object you use this below code.
public void doWorkOnConnection(Session session) {
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
//use the connection here...
}
});
}
if you are looing for a Connection object just to interact with DB in hibernate way.
Session session - HibernateUtil.getSessionFactory().openSession();//or getSession()
Session object here is kind of wrapper class for JDBC conncetion object. you can sue Session object as Connection convention object JDBC procedure.