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.
Related
Hibernate 5.4
The dialect is known, I need to implement the following method :
#Bean
public org.hibernate.SessionFactory sessionFactory(DataSource dataSource) {
// hibernate.dialect = "org.hibernate.dialect.PostgreSQL95Dialect"
// ???
}
Maybe creating one via a Configuration would work for you, as descibed here:
Create Sessionfactory in Hibernate
Configuration cfg = new Configuration()...
.setProperty("hibernate.connection.username", "myuser");
.setProperty("hibernate.connection.password", "mypassword")
.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate_example")
SessionFactory sessionFactory = cfg.buildSessionFactory();
Or you choose to use the Spring LocalSessionFactory-Class like so:
lsfb = new LocalSessionFactoryBean() [from hib5-package]
lsfb.setDataSource( yourDS );
return lsfb.getObject();
Setting the Datasource this might help:
Luiggi Mendoza on SO (How can I set Datasource when I'm creating Hibernate SessionFactory?
)
But if you use a custom data source provider like Apache DBCP or BoneCP and you don't want to use a dependency injection framework like Spring, then you may inject it on the StandardServiceRegistryBuilder before creating the SessionFactory...
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();
Trying to write Dao Test cases for Dropwizard application.
I have implemented my own version to AbstractDaoTest class which has nothing todo with Dropwizard's configuration. Wondering if I can use Dropwizard's hibernate configuration and get session factory from Dropwizard's HibernateBundle.
public AbstractDaoTest() {
Configuration config=new Configuration();
config.setProperty("hibernate.connection.url","jdbc:mysql://127.0.0.1/testme");
config.setProperty("hibernate.connection.username","haha");
config.setProperty("hibernate.connection.password","haha");
config.setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver");
config.setProperty("hibernate.current_session_context_class","thread");
config.setProperty("hibernate.show_sql", "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
sessionFactory = config.buildSessionFactory(serviceRegistry);
}
Is there a way I can get hold of HibernateBundle of Dropwizard in my AbstarctDaoTest class?
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.