How to mock the database session for HSQL DB Junit - java

I have a repository implementation class as below.
public class TesepositoryImpl extends OTPRepositoryBase implements
TestRepository {
public TesepositoryImpl() {
super(RequiresOTPSession.YES);
}
#Override
public int createPreference(AirDetail AirDetail)
throws PersistenceException {
Transaction tx = null;
Session session = null;
try {
session = otpDatabaseSession.openSession();
tx = session.beginTransaction();
session.save(AirDetail);
tx.commit();
} finally {
otpDatabaseSession.closeSession(session);
}
return AirDetail.getAirDetailId().intValue();
}
I have stated writting junit for the above
public class TesRepositoryImplTest {
private EmbeddedDatabase db;
#Before
public void setUp() {
db = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("db/sql/create-db.sql")
.addScript("db/sql/insert-data.sql").build();
}
TesRepository testRepository = new TestRepositoryImpl();
#Test
public void createPreference() throws Exception {
//*setting values** creating preference**/
int airRefereID = testRepository
.createPreference(preference);
}
#After
public void tearDown() {
db.shutdown();
}
i defined hibernate cfg file as below
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:fcds</property>
<property name="connection.username">SA</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.autocommit">true</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.standard_service_registry_builder">false</property>
<mapping class="com.aa.dotc.commons.domain.preference" />
</session-factory>
</hibernate-configuration>
I need to know the below.
When I call testRepository
.createPreference(preference);
I need to override the otpsession to HSQL session.
Kindly help me how to achieve the above using HSQL or share any samples to achieve the same.

Related

Cannot get a connection as the driver manager is not properly initialized on hibernate

I am learning Hibernate and I dont understand why am I getting this error launching program:
java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:172)
at net.codejava.hibernate.VueloManager.setup(VueloManager.java:15)
at net.codejava.hibernate.VueloManager.main(VueloManager.java:54)
hibernate.cfg.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property
name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://127.0.0.1:3306/vuelos_lite</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="net.codejava.hibernate.Vuelo" />
<mapping class="net.codejava.hibernate.Pasajero" />
<mapping class="net.codejava.hibernate.Pasaje" />
</session-factory>
</hibernate-configuration>
VueloManager class. This is the main class of the program:
public class VueloManager {
protected SessionFactory sessionFactory;
protected void setup() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
protected void read() {
Session session = sessionFactory.openSession();
String identificadorId = "BRU-2222";
Vuelo vuelo = session.get(Vuelo.class, identificadorId);
System.out.println("Id: " + vuelo.getIdentificador());
System.out.println("Fecha: " + vuelo.getDate());
System.out.println("Tipo Vuelo: " + vuelo.getTipo_vuelo());
exit();
}
public static void main(String[] args) {
VueloManager manager = new VueloManager();
manager.setup();
//manager.read();
manager.exit();
}
}
I have checked hibernate.cfg.xml connections and all is fine.

StackOverflowError thrown when C3P0 jars are added

I'm writing simple app using Hibernate. I have hibernate.cfg.xml file as follows:
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/demo
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Use the C3P0 connection pool provider -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!--List of XML mapping files -->
<mapping class="www.Message"/>
</session-factory>
</hibernate-configuration>
and retrieve SessionFactory object as follows:
//in HibernateUtil.class
SessionFactory sessionFactory;
Configuration configuration=new
Configuration().configure("hibernate.cfg.xml");
sessionFactory=configuration.buildSessionFactory();`
And everything works fine until I add C3P0 jars:
c3p0-0.9.5.2.jar
hibernate-c3p0-5.2.14.Final.jar
mchange-commons-java-0.2.11.jar
After adding jars above, the app throws StackOverflowError.
Here's my main App class:
package www;
import org.hibernate.Session;
import utils.HibernateUtil;
import java.util.List;
public class HelloWorld {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(new Message("Hello Denmark!"));
session.getTransaction().commit();
session.close();
System.out.println("Message saved...");
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List messages = session.createQuery("from Message m order by m.text
asc").list();
System.out.println("Messages found:"+messages.size());
for (Object mes: messages) {
Message message = (Message) mes;
System.out.println(message.getText());
}
session.getTransaction().commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) session.close();
}
}
}
Any help would be appreciated.

Hibernate - Unable to make JDBC Connection [jdbc:mysql//localhost:3306/hibernatedb

I am trying to create a basic hibernate application using hibernate 5.2.10 release. When I run it it says
org.hibernate.HibernateException: Unable to make JDBC Connection [jdbc:mysql//localhost:3306/hibernatedb]
hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql//localhost:3306/hibernatedb</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.hbm2ddl.auto">udpate</property>
<mapping class="com.chandu.app.model.UserDetails"/>
</session-factory>
Main class:
public class HibernateTest {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails user = getUserObject();
session.save(user);
session.getTransaction().commit();
session.clear();
}
private static UserDetails getUserObject() {
UserDetails user = new UserDetails();
user.setUserName("Test User");
return user;
}
Console:
Code Structure:
I have gone through some of the forums, but couldnt find a solution for the same.
Thanks for the help!
jdbc:mysql//localhost:3306/hibernatedb
Use a colon (:) both before and after "mysql":
jdbc:mysql://localhost:3306/hibernatedb

Hibernate rebuilds tables of DB

I have very simple maven + hibernate project.
I want to retrieve data and print it in console with the command "select * from product". But each time i launch my app, it rebuilds all tables in db, as a result all data is removed.
What should I do so tables are not rerebuilt each time I launch my app?
Main.java
public class Main {
static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
List<Object> products = null;
try {
session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from product");
query.addEntity(Product.class);
products = query.list();
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
sessionFactory.close();
}
System.out.println("Hello");
for (Iterator iterator = products.iterator(); iterator.hasNext(); ) {
Product product = (Product) iterator.next();
logger.info("Hello");
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">****</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.jdbc.lob.non_contextual_creation">true</property>
<mapping class="models.User"/>
<mapping class="models.Role"/>
<mapping class="models.Product"/>
<mapping class="models.ProductCategory"/>
<mapping class="models.Order" />
</session-factory>
</hibernate-configuration>
Change your line
<property name="hbm2ddl.auto">create</property>
by
<property name="hbm2ddl.auto">validate</property>
Look also https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
Use following code in your hibernate.cfg.xml file
<property name="hbm2ddl.auto">Update</property>
instead of
<property name="hbm2ddl.auto">create</property>

Hibernate does not create tables but also throws no errors

Hibernate does not create any tables:
I got a Tomcat server where my jsf/hibernate project runs on. The database server is a MySQL server. Starts without problems but does not create any tables.
I made a new project without the Tomcat server and any other stuff. Only the Hibernate related code. Still no errors and warnings, but also no tables created.
Hibernate config (hibernate.cfg.xml):
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/3bt_database</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hbm2ddl.auto">create</property>
<mapping class="model.Testtable"/>
</session-factory>
</hibernate-configuration>
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionfactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() throws HibernateException {
try {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionfactory(){
return sessionfactory;
}
}
StartStopListener:
#WebListener
public class StartStopListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
HibernateUtil.getSessionfactory().openSession();
}
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
HibernateUtil.getSessionfactory().close();
}
}
Testtable:
#Entity
#Table(name="tblTest")
public class Testtable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int testID;
private String testname;
}
Please do not tell me to create them manually. This is not the answer I am looking for.
try to prepend hibernate. in every propery name
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/3bt_database</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="model.Testtable"/>
</session-factory>
</hibernate-configuration>
Update :-
Provide one more property. try at beginning ..
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
//or try with
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
(Posted on behalf of the OP).
I solved the problem. The mapping setting in the XML was no working properly. This link helped me out very much.

Categories