1.Create HibernateUtil Class Externally
package persistance;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from 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();
}
}
2.Main Class
package FeesCategories;
import org.hibernate.Session;
import java.sql.*;
import persistance.HibernateUtil;
public class AddFessCategory {
public static void send(fees_category fc)
{
try{
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String name=fc.getFees();
// session.save(name);
PreparedStatement ps=(PreparedStatement) session.connection().prepareStatement("insert into fees_category values(null,?)");
ps.setString(1, name);
//System.out.println("success");
int a=ps.executeUpdate();
if(a>0)
{
System.out.println("inserted");
}
session.getTransaction().commit();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
package persistance;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from 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();
}
}
2.Main Class
package FeesCategories;
import org.hibernate.Session;
import java.sql.*;
import persistance.HibernateUtil;
public class AddFessCategory {
public static void send(fees_category fc)
{
try{
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String name=fc.getFees();
// session.save(name);
PreparedStatement ps=(PreparedStatement) session.connection().prepareStatement("insert into fees_category values(null,?)");
ps.setString(1, name);
//System.out.println("success");
int a=ps.executeUpdate();
if(a>0)
{
System.out.println("inserted");
}
session.getTransaction().commit();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
No comments:
Post a Comment