Added DAO for Supplier (#1950)

* First commit for Hibernate 5 Multitenancy tutorial

* Changes to fix the code.

* Added hibernate begin transaction code.

* Changes to solve the multitenancy issue.

* Changes to integrate h2

* Changing configs to solve the error

* Changes to solve h2 error...

* Changes to fix H2 error.

* Cleaned POM.xml and changed entity name

* Changes table name to supplier

* Removed MySql Dep from pom.xml.

* Changes as per comment in the PR...

* Removed try-catch from test functions.

* Removing the hibernate xml config.

* Changed the formatting as per the formatter.

* Clean up after merge.

* # WARNING: head commit changed in the meantime

Merge remote-tracking branch 'upstream/master' into
hibernate5-multitenancy

Conflicts:
	hibernate5/pom.xml
	pom.xml

* Introduced Supplier DAO

* shifting hibernate properties to src/test/resouces

* removed the old test.

* Filled up the stubs in the DAO.
This commit is contained in:
Parth Joshi 2017-06-03 08:48:15 +05:30 committed by KevinGilmore
parent 25de280068
commit 5b0302524f
6 changed files with 123 additions and 80 deletions

View File

@ -0,0 +1,12 @@
package com.baeldung.hibernate.dao;
import java.util.List;
public interface GenericDao<T> {
void save (T entity);
void delete (T Entity);
T findByName(String name);
List<T> findAll();
void populate();
}

View File

@ -0,0 +1,80 @@
package com.baeldung.hibernate.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import com.baeldung.hibernate.pojo.Supplier;
public class SupplierDao implements GenericDao<Supplier>{
private SessionFactory sessionFactory;
private String tenant;
public SupplierDao(SessionFactory sessionFactory, String tenant) {
this.sessionFactory = sessionFactory;
this.tenant = tenant;
populate();
}
@Override
public void save(Supplier entity) {
Session session = sessionFactory.withOptions().tenantIdentifier(tenant).openSession();
session.save(entity);
}
@Override
public void delete(Supplier supplier) {
Session session = sessionFactory.withOptions().tenantIdentifier(tenant).openSession();
session.delete(supplier);
}
@Override
public Supplier findByName(String name) {
Session session = sessionFactory.withOptions().tenantIdentifier(tenant).openSession();
List<Supplier> fetchedSuppliers = session.createCriteria(Supplier.class).add(Expression.eq("name", name)).list();
if (fetchedSuppliers.size()>0) {
return fetchedSuppliers.get(0);
}else {
return null;
}
}
@Override
public List<Supplier> findAll() {
Session session = sessionFactory.withOptions().tenantIdentifier(tenant).openSession();
return session.createCriteria(Supplier.class).list();
}
@Override
public void populate() {
System.out.println("Init DB1");
Session session = sessionFactory.withOptions().tenantIdentifier(tenant).openSession();
Transaction transaction = session.getTransaction();
transaction.begin();
session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
session
.createSQLQuery(
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
.executeUpdate();
Supplier genertedSupplier = generateEntityForTenant(tenant);
System.out.println("Inserting Supplier"+genertedSupplier);
save (genertedSupplier);
}
private Supplier generateEntityForTenant(String forTenant) {
if (forTenant.equals("mydb1")) {
return new Supplier ("John","USA");
}
return new Supplier ("Miller","UK");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.hibernate;
import java.io.IOException;
import org.hibernate.SessionFactory;
import org.junit.Test;
import com.baeldung.hibernate.dao.SupplierDao;
import com.baeldung.hibernate.pojo.Supplier;
import static org.junit.Assert.assertNull;;
public class MultiTenantDaoHibernateIntegrationTest {
@Test
public void givenDBMode_whenFetchingSuppliersByName_thenChecking() throws UnsupportedTenancyException, IOException {
SessionFactory sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
SupplierDao myDb1Dao = new SupplierDao(sessionFactory, "mydb1");
Supplier db1SupplierName = myDb1Dao.findByName("John");
// finding the same supplier name in another tenant
// and we should not be able to find in there and both dbs are different.
SupplierDao myDb2Dao = new SupplierDao(sessionFactory, "mydb2");
Supplier db2SupplierName = myDb2Dao.findByName(db1SupplierName.getName());
assertNull(db2SupplierName);
}
}

View File

@ -1,72 +0,0 @@
package com.baeldung.hibernate;
import static org.junit.Assert.assertNotEquals;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.pojo.Supplier;
public class MultiTenantHibernateIntegrationTest {
@Test
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs() throws UnsupportedTenancyException, IOException {
SessionFactory sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
Session db1Session = sessionFactory.withOptions().tenantIdentifier("mydb1").openSession();
initDb1(db1Session);
Transaction transaction = db1Session.getTransaction();
transaction.begin();
Supplier supplierFromDB1 = (Supplier) db1Session.createCriteria(Supplier.class).list().get(0);
transaction.commit();
Session db2Session = sessionFactory.withOptions().tenantIdentifier("mydb2").openSession();
initDb2(db2Session);
db2Session.getTransaction().begin();
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
db2Session.getTransaction().commit();
System.out.println(supplierFromDB1);
System.out.println(supplierFromDB2);
assertNotEquals(supplierFromDB1, supplierFromDB2);
}
private void initDb1(Session db1Session) {
System.out.println("Init DB1");
Transaction transaction = db1Session.getTransaction();
transaction.begin();
db1Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
db1Session
.createSQLQuery(
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
.executeUpdate();
db1Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'John', 'USA')").executeUpdate();
transaction.commit();
}
private void initDb2(Session db2Session) {
System.out.println("Init DB2");
Transaction transaction = db2Session.getTransaction();
transaction.begin();
db2Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
db2Session
.createSQLQuery(
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
.executeUpdate();
db2Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'Miller', 'UK')").executeUpdate();
transaction.commit();
}
}

View File

@ -1,8 +0,0 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.multiTenancy=DATABASE

View File

@ -1,6 +1,7 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect