Error while connecting Mysql db with java using hibernate - java

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();

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

Access SSL-Parameters in connections via Hibernate

I am using a hibernate java application which uses a sessionfactory to create connections and sessions. As i am using it with a postgresql database i pass the proper jdbc connectionstring to build the sessionfactory and get my sessions from it afterwards. The only thing im able to access is the jdbc4connection.
How am i able to read which ciphersuite is used within the secured connection, which SSL protocol is used etc?
Here is how i initialize my sessionfactory:
Configuration configuration = new Configuration();
Properties p = configuration.getProperties();
p.setProperty("hibernate.connection.url","jdbc:postgresql://127.0.0.1:5432/postgres?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory");
p.setProperty("hibernate.connection.username", "myusername");
p.setProperty("hibernate.connection.password", "mypassword");
p.setProperty("hibernate.connection.driver_class",
"org.postgresql.Driver");
p.setProperty("hibernate.dialect",
"org.hibernate.dialect.PostgreSQLDialect");
ServiceRegistry serviceRegistryWebOnkys = new StandardServiceRegistryBuilder()
.applySettings(p).build();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistryWebOnkys);
If you can find out how to do it with via regular JDBC (I don't know how it's done), then you can do the same thing with Hibernate.
session.doWork(new Work() {
#Override
public void execute(Connection connection) throws SQLException {
// access the connection here and perform regular jdbc operations.
}
});
This is what I had to do when I had set some Oracle specific properties that could be set only on "OracleConnection.java" instances.
oracle.jdbc.driver.OracleConnection oc = (oracle.jdbc.driver.OracleConnection) connection.getMetaData().getConnection()

Hibernate session factory close drops all auto generated tables

Using hibernate4
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
//do some task
session.getTransaction().commit();
session.close();
factory.close();
Using auto generated proprty
<property name="hibernate.hbm2ddl.auto">create-drop</property>
as you can see I am closing my session factory it drops all my tables after this code completed as I see on console. Is it the default behaviour
This is expected behavior for the create-drop mode.
See this documentation for more information.
Additionally, see this article for more exposition on the values.
That's the intention of the property create-drop.
Use create or update to keep your tables.
change hbm2dll.auto property in your hibernate mapping to "update" to keep the changes you do in the database.

How to read hibernate config file from user defined directory

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");

Categories

Resources