com.zettsy.serverping.dao.PingDataImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.zettsy.serverping.dao.PingDataImpl.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zettsy.serverping.dao;

import com.zettsy.serverping.config.ApplicationContextConfig;
import java.util.HashMap;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class PingDataImpl implements PingDataDao {

    @Autowired
    private SessionFactory sessionFactory;

    private ApplicationContextConfig applicationContextConfig = new ApplicationContextConfig();

    public PingDataImpl() {

    }

    public PingDataImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @Transactional
    public void addPingData(PingData pingData, SessionFactory sessionFactory) {
        Session session = sessionFactory.getCurrentSession();
        Transaction trans = session.beginTransaction();
        session.save(pingData);
        trans.commit();
    }

    @Override
    @Transactional
    public SessionFactory addDataBase(String sid, HashMap myMap) {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/" + "hrdtechn_" + sid);
        dataSource.setUsername("hrdtechn_javaapp");
        dataSource.setPassword("root123");

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(applicationContextConfig.getHibernateProperties());
        sessionBuilder.addAnnotatedClasses(PingData.class);
        SessionFactory sessionFactory = sessionBuilder.buildSessionFactory();

        myMap.put(sid, sessionFactory);

        return sessionFactory;
    }

}