How to read hibernate config file from user defined directory - java

I need to provide a jar file which provides an API to retrieve the records from the database using Hibernate.
For example I have an API:
public List getUsers(String locationOfHibernateConfigFile) {
}
I tried by passing the location of the config file with the complete path using c:\hibernate-cfg.xml as shown below:
SessionFactory sessionFactory = new Configuration()
.configure(C:\hibernate.cfg.xml).buildSessionFactory();
session = sessionFactory.openSession();
I am getting an error saying c:\hibernate-cfg.xml is not found.
Please provide me some pointers to achieve the same.

SessionFactory sessionFactory = new Configuration()
.configure("hibernate.primaryKeys.cfg.xml")
.buildSessionFactory();
Where hibernate.primaryKeys.cfg.xml is a user-defined hibernate file.
This will work, but ensure hibernate.primaryKeys.cfg.xml is in your classpath.

Well try it:
File file = new File("C:\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(file).buildSessionFactory();
But it is not advisable to leave this type of configuration on C:.

You can read file and properties:
Just put your file hibernate.cfg.xml into the resources folder.
Properties properties = new Configuration().configure().getProperties();
String driver = properties.getProperty("hibernate.connection.driver_class");
String url = properties.getProperty("hibernate.connection.url");
String username = properties.getProperty("hibernate.connection.username");
String password = properties.getProperty("hibernate.connection.password");

Related

Hibernate - non-working code an what is a service-registry

I just got through the book "Just Hibernate" from O'Reilly. Some code isn't really explained fully but just given without complete description.
This code for example:
public class BasicMovieManager {
private SessionFactory sessionFactory = null;
// Creating SessionFactory using 4.2 version of Hibernate
private void initSessionFactory(){
Configuration config = new Configuration().configure();
// Build a Registry with our configuration properties
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
// create the session factory
sessionFactory = config.buildSessionFactory(serviceRegistry);
}
...
}
I just wanted to copy the code to my Hibernate-experiments, but the current stable Hibernate-version 5.2 doesn't know the class ServiceRegistryBuilder. What is a service-registry and how do I have to change the code to work with the current Hibernate-version?
The code was used to create a SessionFactory with Hibernate 4.x
The similar code for Hibernate 5.x would be something like:
StandardServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metaData =
new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
As you can see, in Hibernate 5 StandardServiceRegistry class is used. If you don't have a hibernate.cfg.xml file just use configure() method with no arguments.
See this article for further details.

Why I am unable to initialize Service Registry( Hibernate) via Servlets?

public static void main(String args[]) {
System.out.println("<<++++++++INITIALIZED+++++++>>");
final Configuration configuration = new Configuration().configure();
final StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
// Session Factory
factory = configuration
.buildSessionFactory(builder.build());
// Open Session
session = factory.openSession();
session.beginTransaction();
}
public static void checkNow(String name,String email,String pass,String phone){
System.out.println("<<++++++++INITIALIZED+++++++>>");
main(null);
System.out.println("<<++++++++INITIALIZED+++++++>>");
Transaction tx= session.beginTransaction();
User user = new User();
user.setpersonal_Name(name);
user.setpersonal_Email(email);
user.setpersonal_Password(pass);
user.setpersonal_Phone(phone);
tx.begin();
System.out.println("<<+++++++SAVING++++++>>>");
session.save(user);
tx.commit();
session.close();
factory.close();
}
In this code User properties coming from linked html Servlet and from that Servlet I am calling a method of concrete class i.e "CheckData.java",If I run this code with main method its working fine Table created and If I run this from whole process that is, from Web (Appache Tomcat) Its giving me error of ClassNotFoundException ServiceRegistry.Solution required ASAP.This is my Project Explorer having some html,css and java classes / servlets.Dynamic Web Project Using Appache Tomcat Server,My Exception Screenshot here
Actually The Problem Was with Libraries where I was putting them
See my Project Explorer I have put them in just right place but in case of Dynamic Web Project , We have to define Libraries not only as a "Build Path" but also in lib folder Under "Web Content" Folder too .
Thanks Everyone who at least viewed Once

Configuring the database properties from outside of intellij

I want to ask as currently I have my database properties like username and password inside the persistence layer in the intellij. But I want to place it somewhere outside so if someone wants to change the password or any configuration inside database he should not have to dig inside my current structure. Now my structure is persistence then main then resources and then dbconfig properties so is there any way I can do it.
You can create a file app.properties in your resources folder with all database information you need:
# Datasource details
testapp.db.driver = org.h2.Driver
testapp.db.url = jdbc:h2:mem:test
testapp.db.username = username
testapp.db.password = password
Then you can refer to it in your Java code as:
#Configuration
#PropertySource("app.properties")
public class DataConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(env.getProperty("testapp.db.driver"));
ds.setUrl(env.getProperty("testapp.db.url"));
ds.setUsername(env.getProperty("testapp.db.username"));
ds.setPassword(env.getProperty("testapp.db.password"));
return ds;
}
}

Error while connecting Mysql db with java using hibernate

I was trying to connect a simple java application with mysql db using hibernate. I have already created the schema in my db and this java application is simply creating a table in this schema and inserting data in it.All the time I am getting same error.
My Code is as follows:
hibernate.cfg.xml
UserDetails.java
HibernateTest.java
Error:
Please help me, I have been stuck for quite a long time.
Thanks !!
Seems like a duplicate of Exception in thread "main" java.util.ServiceConfigurationError
Seems that your using hibernate >=4 and the setup procedure from hibernate <4.
Correct way according to the link is.
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
//check External Jar files whether you added properly or not...if not remove all jar files and add once again...
After Main
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.OpenSession();
UserDetails ud = new UserDetails();
ud.setName("bdskbf");
ud.setId(23);
Transaction tnx = session.beginTransaction();
session.save(ud);
tnx.getTransaction.commit();

Location of hibernate.cfg.xml in project?

I created a project with following structure:
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
at line
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
I have error
Initial SessionFactory creation
failed.org.hibernate.HibernateException:
C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml
not found Exception in thread "main"
java.lang.ExceptionInInitializerError at
logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at
logic.HibernateUtil.(HibernateUtil.java:9) at
logic.Main.main(Main.java:12) Caused by:
org.hibernate.HibernateException:
C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml
not found at
org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
at
org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1947)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1928)
at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 2 more
What is the reason for the error and how do I fix it?
Give the path relative to your project.
Create a folder called resources in your src and put your config file there.
configuration.configure("/resources/hibernate.cfg.xml");
And If you check your code
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();
In two lines you are creating two configuration objects.
That should work(haven't tested) if you write,
Configuration configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return configuration.buildSessionFactory();
But It fails after you deploy on the server,Since you are using system path than project relative path.
Somehow placing under "src" folder didn't work for me.
Instead placing cfg.xml as below:
[Project Folder]\src\main\resources\hibernate.cfg.xml
worked.
Using this code
new Configuration().configure().buildSessionFactory().openSession();
in a file under
[Project Folder]/src/main/java/com/abc/xyz/filename.java
In addition have this piece of code in hibernate.cfg.xml
<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />
Placed the above hbm.xml files under:
EDIT:
[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml
Above structure worked.
You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:
Configuration configuration = new Configuration();
sessionFactory =configuration.configure().buildSessionFactory();
This is an reality example when customize folder structure:
Folder structure, and initialize class HibernateUtil
with:
return new Configuration().configure("/config/hibernate.cfg.xml").buildSessionFactory();
mapping:
with customize entities mapping files:
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.vy.entities.Users"/>
<mapping class="com.vy.entities.Post"/>
<mapping resource="config/Users.hbm.xml"/>
<mapping resource="config/Post.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(Note: Simplest way, if you follow default way, it means put all xml config files inside src folder, when build sessionFactory, only:
return new Configuration().configure().buildSessionFactory();
)
For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml under src/main/resources.
try below code it will solve your problem.
Configuration configuration = new Configuration().configure("/logic/hibernate.cfg.xml");
My problem was that i had a exculding patern in the resorces folder.
After removing it the
config.configure();
worked for me. With the structure
src/java/...HibernateUtil.java and cfg file under src/resources.
Another reason why this exception occurs is if you call the configure method twice on a Configuration or AnnotatedConfiguration object like this -
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(MyClass.class);
//Use this if config files are in src folder
config.configure();
//Use this if config files are in a subfolder of src, such as "resources"
config.configure("/resources/hibernate.cfg.xml");
Btw, this project structure is inside eclipse.
Using configure() method two times is responsible the problem for me. Instead of using like this :
Configuration configuration = new Configuration().configure();
configuration.configure("/main/resources/hibernate.cfg.xml");
Now, I am using like this, problem does not exist anymore.
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too.
The code belove works for me. at hibernate-5
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
try{
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
catch(Exception e){
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
In case of a Maven Project, create a folder named resources under src/main folder and add the resources folder as a source folder in your classpath.
You can do that by going to Configure Build Path and then clicking Add Folder to the Sources Tab.
Then check the resources folder and click Apply.
Then just use :
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Categories

Resources