07. Spring – Creating database connection.

 


Creating database connection.

මෙහිදී database configurations කල හැකි ආකාර 2කි.

01. Using Java class.

02. Using XML file.


01.     Using Java class.

@Configuration

@ComponentScan (basePackages={"com.lhu.backend.dto"})

@EnableTransactionManagement

public class HibernateConfig{}

In hibernate we required a data source, session factory which provide some sessions and using those sessions we can create and execute queries and those executes quarries should be managed within transaction.

@Configuration – telling about we are creating some configuration class and that been should be handle by spring.

@ComponentScan(basePackages={"com.lhu.backend.dto"}) - Telling where the entity class are located that hibernate required.

@EnableTransactionManagement  – telling to spring to enable the transaction management. we are not going to handle it.

 

In here needs to create 3 beans - @Bean

1.      DataSourse – providing connection information of the data base.

2.      SessionFactory – Configure the application to use hibernate and then provide a session object. It is used the data source and it provides a session for particular user. Using this session user create queries and then it will execute within the transaction.

3.      HibernateTransactionManagement  -to manage the hibernate transactions

 

Needs to match with hibernate version which you are using.(if you are using version 5) If org.springframework.orm.hibernate4.HibernateTransactionManager 

this should be change as 

org.springframework.orm.hibernate5.HibernateTransactionManager

 

import org.springframework.orm.hibernate5.HibernateTransactionManager;

import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;

 

All the entity class (used to transfer the data to the relational database) which related to the database should be annotated with @Entity. Class name (entity name) should be same name with database name. Unless you want to change it.

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages={"com.lhu.backend.dto"})
@EnableTransactionManagement
Public class HibernateConfig {

// Change the below based on the DBMS you choose
Privatefinalstatic String DATABASE_URL = "jdbc:mysql://localhost:3306/onlineshopping";
Privatefinalstatic String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
Privatefinalstatic String DATABASE_DIALECT = "org.hibernate.dialect.MySQLDialect";
Privatefinalstatic String DATABASE_USERNAME = "root";
Privatefinalstatic String DATABASE_PASSWORD = "root";
// dataSource bean will be available
@Bean("dataSource")
Public DataSource getDataSource() {
BasicDataSourcedataSource = newBasicDataSource();
// Providing the database connection information
dataSource.setDriverClassName(DATABASE_DRIVER);
dataSource.setUrl(DATABASE_URL);
dataSource.setUsername(DATABASE_USERNAME);
dataSource.setPassword(DATABASE_PASSWORD);
return dataSource;
}
// sessionFactory bean will be available
@Bean
Public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("com.lhu.backend.dto");
return builder.buildSessionFactory();
}
// All the hibernate properties will be returned in this method
Private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", DATABASE_DIALECT);
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
//properties.put("hibernate.hbm2ddl.auto", "create");
return properties;
}
// transactionManager bean
@Bean
Public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}


That connection can be used as bellows.


import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("cartLineDAO")
@Transactional
Publicclass CartLineDAOImpl implements CartLineDAO {
@Autowired
Private SessionFactory sessionFactory;
@Override
Publicboolean addUpdateRemove(CartLinecartLine) {
try {
sessionFactory.getCurrentSession().persist(cartLine);
sessionFactory.getCurrentSession().update(cartLine);
sessionFactory.getCurrentSession().delete(cartLine);
return true;
}catch(Exception ex) {}
}

@Override
publicCartLine get(int id) {
return sessionFactory.getCurrentSession().get(CartLine.class, Integer.valueOf(id));
}

@Override
Public List<Category> list() {
String selectActiveCategory = "FROM Category WHERE active = :active";
Query query = sessionFactory.getCurrentSession().createQuery(selectActiveCategory);
query.setParameter("active", true);
return query.getResultList();
}
@Override
Public CartLine getByCartAndProduct(intcartId, intproductId) {
Stringquery = "FROM CartLine WHERE cartId = :cartId AND product.id = :productId";
return sessionFactory.getCurrentSession()
.createQuery(query,CartLine.class)
.setParameter("cartId", cartId)
.setParameter("productId", productId)
.getSingleResult();
}

@Override
Public List<CartLine> listAvailable(int cartId) {
String query = "FROM CartLine WHERE cartId = :cartId AND available = :available";
return sessionFactory.getCurrentSession()
.createQuery(query, CartLine.class)
.setParameter("cartId", cartId)
.setParameter("available", true)
.getResultList();
}

@Override
Public List<Product> getLatestActiveProducts(int count) {
return sessionFactory
.getCurrentSession()
.createQuery("FROM Product WHERE active = :active ORDER BY id", Product.class)
.setParameter("active", true)
.setFirstResult(0)
.setMaxResults(count)
.getResultList();
}
}


Other way to do it.

01.     Using XML file.


Do all configurations in a xml file.

Adding database configuration file as XML file

Right click on the project – new – other – search hibernate and select Hibernate Configuration File(cfg.xml) – next – then file can be change or not (if it is change that name should be manually provided  in the place where hibernate configuration file name should be provided. It also explain bellow) – next provide related information and finish.

ඒසේ සදෙන XML file එකේ default name එක hibernate.cfg.xml වේ.නමුත් අප custom file name  එකක් යොදාගන්නේ නම් (eg: hibernateConfigure.cfg.xml ) ඒ නම පහත පරිදි code එක තුලදී ලබදිය යුතුය.

Configuration con = new Configuration ().configure(“hibernateConfigure.cfg.xml “);

නමුත් default name  එක බාවිතා වන්නේ නම් code එක තුලදී  ඒ නම සදහන් කිරීම අවශ්‍යම නොවේ.

Configuration con = new Configuration().configure();






Hibernate.cfg.xml FILE

////////////////////////////////////////////////////////////////////////////////////////

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEhibernate-configurationPUBLIC

               "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

               "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

<session-factory>

<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<propertyname="hibernate.connection.password">root</property>

<propertyname="hibernate.connection.url">

jdbc:mysql://localhost:3306/JerseyRestCompay

</property>

<propertyname="hibernate.connection.username">root</property>

<propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

 

<propertyname="hbm2ddl.auto">update</property>

<propertyname="show_sql">true</property>

 

</session-factory>

</hibernate-configuration>

////////////////////////////////////////////////////////////////////////////////////////

 

<property name="hbm2ddl.auto">update</property>

 

This tells whether data base table should be newly created or updates.

Java class කලින් හදාගෙන ඊටපස්සේ ඒ class වලින් database එකේ table හැදෙන්න ඕනෙනම් පලවෙනි පර project එක run කරද්දී create ලෙස තිබියවේ.මෙවිට database එකේ අලුතෙන් table සදගනී.උදාහරණයක් ලෙස Employee entity class එක අපි java වල හදල එකකට employee කියලා table එකක් database හදාගන්න ඕනෙනම් create ලෙස තිබ්බම අලුතෙන් එකක් සාදාගනී.employee කියලා table එකක් තිබ්බොත් එක delete කරලා යේ අලුතෙන් එකක් සදයි.නමුත් update ලෙස තිබ්බම වෙන්නේ database එකේemployee කියලා table එකක් තියනවනම් එක update වෙන එකියි.එහෙමtable එකක් නැත්තම් එක error එකක් ලෙස එනවා.

<property name="show_sql">true</property>

 

අපි hibernate වලදී බාවිතා කරන්නේ HQL හෙවත් hibernate query language වේ.නමුත් hibernateවලදී එය SQL වලට convert කරවාගෙන තමා database hit වීමවෙන්නේ.එහිදී අපිට අප දෙන HQL එකට අදාළ SQL  එක බලාගන්න ඕනෙනම්, ඉහත පරිදී (Hibernate.cfg.xml තුල)දෙන්න ඔනී.මෙවිට HQL  වලට අදාළSQL query console එකේ බලාගත හැක.

package com.lahiru.daoImpl;
import com.lahiru.dao.HotelDao;
import com.lahiru.dto.City;
import com.lahiru.dto.Hotels;
import java.nio.channels.SeekableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.springframework.stereotype.Repository;

@Repository("hotelDaoImpl")
public class HotelDaoImpl implements HotelDao{

public static Session sessionBulder(){
Configuration con = new Configuration().configure().addAnnotatedClass(City.class).addAnnotatedClass(Hotels.class);
ServiceRegistry reg = new ServiceRegistryBuilder().applySettings(con.getProperties()).buildServiceRegistry();
SessionFactory sf = con.buildSessionFactory(reg);
Session session = sf.openSession();
return session;
}
@Override
public List getCityNames(){
Session session = HotelDaoImpl.sessionBulder();
SQLQuery Squery = session.createSQLQuery("select * from city");
List<Object[]> nm = (List<Object[]>) Squery.list();
List<City> city = new ArrayList<City>();
City c ;
for (Object[] ct: nm){
c = newCity();
c.setCity_code((Integer)ct[0]);
c.setCity_name((String)ct[1]);
city.add(c);
}
return city;
}

@Override
public List<City> cityInfo(){
Session session = HotelDaoImpl.sessionBulder();
Query query = session.createQuery("from City");
List list = query.list();
return list;
}
@Override
public List<City> getAllHotels(){
Session session = HotelDaoImpl.sessionBulder();
Query query = session.createQuery("from Hotels");
List list = query.list();
return list;
}

@Override
public List<City> getSelectedCityHotels(int city_code){
Session session = HotelDaoImpl.sessionBulder();
Query query = session.createQuery("from Hotels where city_code = ?");
query.setParameter(0, city_code);
List list = query.list();
return list;
}

@Override
public Hotels getOneHotelInfo(int hotel_id){
Session session = HotelDaoImpl.sessionBulder();
Query query = session.createQuery("from Hotels where hotel_id = ?");
query.setParameter(0, hotel_id);
Hotels ht = (Hotels) query.uniqueResult();
return ht;
}

@Override
public String insertHotelInfo(String name, String address, int city_code,String Image_name){
Session session = HotelDaoImpl.sessionBulder();
Hotels ht = new Hotels();
ht.setHotel_address(address);
ht.setHotel_name(name);
ht.setCity_code(city_code);
ht.setImage_name(Image_name);
Transaction tx = session.beginTransaction();
session.save(ht);
session.getTransaction().commit();
session.close();
return "Successfully Added";
}


@Override
public List<City> getSearchedHotels(String q,int b) {
Session session = HotelDaoImpl.sessionBulder();
Query query=null;
if(b==0&& q==null){
query = session.createQuery("from Hotels");
}
elseif(b==0){
query = session.createQuery("from Hotels where hotel_name like ?");
query.setParameter(0, "%"+q+"%");
}
elseif(q==null){
query = session.createQuery("from Hotels where city_code = ?");
query.setParameter(0, b);
}
else{
query = session.createQuery("from Hotels where city_code = ? and hotel_name like ?");
query.setParameter(0, b);
query.setParameter(1, "%"+q+"%");
}
Listlist = query.list();
return list;
}

}


Comments

Popular posts from this blog

09.Data Binding.

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.