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
Related
I'm using Hibernate withhout #annotations
I tried this code:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static StandardServiceRegistryBuilder builder;
static {
try {
Configuration configuration = new Configuration().configure();
configuration.configure("hibernate.cfg.xml");
builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (HibernateException ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Client code:
public static void main (String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Customer.class);
List<Customer> customers = criteria.list();
for (Customer customer : customers) {
//print values
}
session.getTransaction().commit();
session.close();
}
Also here is important thing I want to know
What if I will create HibernateUtil class object in Client class?
HibernateUtil hibernateUtil = new HibernateUtil();
You can refer stackoverflow link:
What are the advantages and disadvantages of creating an Object in static block in Java?.
If you want SessionFactory to be created when your server or application starts, then static block can be used. else, go for static method approach. You can also use enums to create singleton.
So, you've got two questions there, one about this being the right approach to create a singleton, and the other about what happens if you create a HibernateUtil instance in the client.
First for the HibernateUtil
For the second question, you're fine if each client creates an instance of the HibernateUtil class, as the variable is static. If all goes according to plan, there will only be one Hibernate SessionFactory instance.
As for whether you have a correct Hibernate SessionFactory singleton implementation? That's a harder question to answer. While your code looks good, multiple classloaders can cause all sorts of unpredictable problems with singletons. If separate classloaders create an instance, you may have multiple instances of your singleton, a paradox you want to avoid.
EJB and Spring Singleton help
With the EJB specification, you can mark a session bean as a singleton. If you are using a Java web profile compliant server, I'd do that. If you are using Spring Boot, use the singleton facilities they provide. If it's a standalone application, keep an eye out for peculiar, non-singleton SessionFactory behavior.
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();
I try to configure my EntityManager programmatically. My vendor is OpenJPA and I write a simple console application. Here is my code
public static void main(String[] args) {
Map<String, String> properties = new HashMap<>();
properties.put("openjpa.ConnectionDriverName", "org.postgresql.Driver");
properties.put("openjpa.ConnectionURL", "jdbc:postgresql://localhost:5432/shop");
properties.put("openjpa.ConnectionUserName", "bob");
properties.put("openjpa.ConnectionPassword", "secret");
properties.put("openjpa.RuntimeUnenhancedClasses", "supported");
properties.put("openjpa.MetaDataFactory", "jpa(Types=de.jpa.demo.dto.Category;de.jpa.demo.dto.User;de.jpa.demo.dto.Order;de.jpa.demo.dto.Product)");
properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(foreignKeys=true)");
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test", properties);
OpenJPAConfiguration configuration = ((EntityManagerFactoryImpl) factory).getConfiguration();
MetaDataRepository repositoryInstance = configuration.getMetaDataRepositoryInstance();
repositoryInstance.addPersistenceAware(Category.class);
repositoryInstance.addPersistenceAware(Order.class);
repositoryInstance.addPersistenceAware(Product.class);
repositoryInstance.addPersistenceAware(User.class);
manager = factory.createEntityManager();
}
But I get an error
javax.persistence.PersistenceException: No persistence providers available for "test" after trying the following discovered implementations: org.apache.openjpa.persistence.PersistenceProviderImpl
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:182)
at de.jpa.demo.dto.OpenJpaUserRepositoryIT.init(OpenJpaUserRepositoryIT.java:56)
at de.jpa.demo.dto.OpenJpaUserRepositoryIT.before(OpenJpaUserRepositoryIT.java:22)
What I'm doing wrong?
You must have a META-INF/persistence.xml file with a persistence unit named 'test' in it.
Also, please please please remove openjpa.RuntimeUnenhancedClasses property. It is a buggy feature and you'll be much happier if you take the time to figure out another enhancement strategy.
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");
I have been learning to use hibernate for a couple of months.
I am finding it difficult in deciding how to configure hibernate to work on a test database.
I have a hibernate.cfg.xml with db parameters given as elements.
<property name="connection.url">
jdbc:postgresql://localhost/mydb
</property>
<property name="connection.username">me</property>
<property name="connection.password">mypasswd</property>
My web app uses a HibernateUtil class which loads the configuration as below
class HibernateUtil {
private Class<T> persistentClass;
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
...
My dao implementation uses the above class to get the Session
public class BaseDaoImpl<T, ID extends Serializable>{
private Session session;
...
public Session getSession() {
if (session == null || !session.isOpen()){
return HibernateUtil.getCurrentSession();
}else{
return session;
}
}
public T findById(ID id){
T entity = (T) getSession().load(getPersistentClass(), id);
return entity;
}
This is OK as long as I work on the mydb configured in cfg.xml file.But for my tests I am using another database which is given in a test.properties file
test.db.url=jdbc:postgresql://localhost/mytestdb
test.db.driver=org.postgresql.Driver
test.db.username=testme
test.db.password=testpass
The only way I can make hibernate work on mytestdb is to manually replace every db related property in cfg.xml.I would very much like to use test_hibernate.cfg.xml with the test db properties,but since the configuration is done in a static block in HibernateUtil ,that won't work.
Is there a better way of configuring hibernate for these two databases?
I am using ant as build tool..
Any suggestions would be most welcome
jim
I would very much like to use test_hibernate.cfg.xml with the test db properties,but since the configuration is done in a static block in HibernateUtil
So then don't create your configuration in a static block.
Instead, create a class which accepts a parameter for the path to the configuration file (a la Spring's LocalSessionFactoryBean) which returns the Configuration/SessionFactory to use. Or if you truly want to stick with HibernateUtil (which is a strategy very much recommended against in any production setting), change it to read a property or system environment variable to read the configuration.