Try something like this(class HibernateUtil): package initHb;
import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration;
/** * * @author morar */ public class HibernateUtil { private static SessionFactory sessionFactory; private static StandardServiceRegistry serviceRegistry; public static SessionFactory createSessionFactory(String dbName, String dbUser, String dbPwd, String[] mapClass ) throws ClassNotFoundException{ // change params Configuration cfg = new Configuration(); cfg.configure(); for(int i = 0; i < mapClass.length; i++){ Class c = Class.forName(mapClass[i]); cfg.addAnnotatedClass(c);//.configure(); } cfg.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/" + dbName); cfg.setProperty("hibernate.show_sql", "false"); cfg.setProperty("hibernate.connection.username", dbUser); cfg.setProperty("hibernate.connection.password", dbPwd); serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); sessionFactory = cfg.buildSessionFactory((org.hibernate.service.ServiceRegistry) serviceRegistry); return sessionFactory; } }
// You can set anything, anythime, anywhere... Works nice(NetBeans 8.1, Java1.8(Oracle) ScientificLinux 6.7 32 bit, MariaDb 10.1 // Hibernate 4.3 , mysql-connector-java-5.1.23-bin.jar // I prefer to use, annotation
/* Hibernate.cfg.xml file */ <?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.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my_test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"/> <!-- <mapping class="docs.DocType"/> --> <property name="hibernate.bytecode.use_reflection_optimizer">true</property> </session-factory> </hibernate-configuration>
|