mapping a collection in hibernate - java

The following code is the service layer which contains a map with some key value pairs.
{1=A, 2=B, 3=c, 4=D}
I want to store this in oracle database using hibernate.I do this previously using Model class mapping but i want to do this mapping to this collection.
public class CollectionMapping {
public static void main(String[] args) {
LinkedHashMap map = new LinkedHashMap();
map.put(1, "A");
map.put(2, "B");
map.put(3, "c");
map.put(4, "D");
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(map);
session.getTransaction().commit();
}
}
The following is hibernate config file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">Oracle Driver</property>
<property name="connection.url">URL</property>
<property name="connection.username">UserName</property>
<property name="connection.password">PassWord</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
this mapping class is for model class but how to do mapping for above collections
// <mapping class="org.symp.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>

I'm not sure what your database schema that you are trying to map to looks like, but this should help:
https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/collections.html

Related

Caused by: org.postgresql.util.PSQLException: database doesn't exist when trying to auto-create database

I have this hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">
jdbc:postgresql://localhost/DatabaseName?createDatabaseIfNotExist=true
&useUnicode=yes&characterEncoding=UTF-8
</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.main.User"/>
</session-factory>
</hibernate-configuration>
which is supposed to create both tables (for the User entity and the database DatabaseName). However, it doesn't create a database and fails with an error on this line:
sessionFactory = configuration.buildSessionFactory();
What can I do to make it autocreate database titled DatabaseName?
To create database you have to create is manually you can use IDEs for that or cmd to create your DB
And To create Tables you can use create in place of update
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
It will create a schema and then you will use an update for the next startup if you don`t want to recreate your tables

How to do bootstrap initialize hibernate in a maven web project?

How to do bootstrap initialize hibernate in a maven web project?
public class HibernateTest {
public static void main(String [] args) {
UserData us1 = new UserData();
us1.setfName("amit");
return "hello";
}
}
It cannot be done by the above code, where UserData is an entity.
First declare dependency for hibernate in pomm.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
Next create configuration file hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/UserDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- <property name="FOREIGN_KEY_CHECKS">0</property> -->
<!-- Mapping files -->
<mapping class="com.stackoverflow.model.Person" />
<mapping class="com.stackoverflow.model.Phone" />
</session-factory>
</hibernate-configuration>
If you have your entities you should list them in tag <mapping class="pathToEntity">.
Next in main method :
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
.build();
try {
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had
// trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy(registry);
System.out.println("Exception\n" + e);
}
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Here you create Sessionfactory and get current Session object to be able to query database.

Hibernate: the session factory does not read the entity mapping from hibernate.cfg.xml

This is my hibernate.cfg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Connessione al database -->
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:xe
</property>
<!-- Credenziali -->
<property name="hibernate.connection.username">Test</property>
<property name="connection.password">Test</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.Oracle10gDialect</property>
<!-- DISABILITA AUTO COMMIT -->
<property name="hibernate.connection.autocommit">true</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<!-- Entity -->
<mapping class= "it.test.Tbl1"></mapping>
<mapping class= "it.test.Tbl2"></mapping>
<mapping class= "it.test.Tbl3"></mapping>
<mapping class= "it.test.Tbl4"></mapping>
</session-factory>
</hibernate-configuration>
and this the hibernate util file:
When i try to execute a simple query, i got the exception as -> "query exception: table not mapped".
But if i change the hibernate util as follows,
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = createSessionFactory();
return sessionFactory;
}
}
the program works with success.
Why the session factory doesn't gets loaded through configuration file?
console log:
10:54:44.989 [main] DEBUG org.hibernate.hql.internal.ast.ErrorCounte-
throwQueryException() : no errors
10:54:45.130 [main] DEBUG
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker - select << begin
[level=1, statement=select]
org.hibernate.hql.internal.ast.QuerySyntaxException: Tbl1 is not mapped
[from Tbl1 eat where eat.activityId = :id]
at
org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException
(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString
(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile
(QueryTranslatorImpl.java:218)
i think that the problem is this :
17:14:47.130 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry -
Registering SessionFactory: a0044811-5a9f-483a-8ede-b136c9781bb3
(<unnamed>)
17:14:47.130 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry -
Not binding SessionFactory to JNDI, no JNDI name configured
17:14:47.364 [main] DEBUG org.hibernate.stat.internal.StatisticsInitiator
- Statistics initialized [enabled=false]
can you help me??
While using method addAnnotatedClass you incoded Tbl1, Tbl2, Tbl3 (2 times) as mentioned in the code which is just edited and removed. .addAnnotatedClass(Tbl1.class).addAnnotatedClass(Tbl2.class).addAnnotatedClass(Tbl3.class).addAnnotatedClass(Tbl3.class).
While using xml configuration you are saying that you have four annotated classes. As mentioned
<mapping class= "it.test.Tbl1"></mapping>
<mapping class= "it.test.Tbl2"></mapping>
<mapping class= "it.test.Tbl3"></mapping>
<mapping class= "it.test.Tbl4"></mapping>
Please check if mapping for Tbl4.class exists or not or try to modify last addAnnotatedClass(Tbl3.class) to .addAnnotatedClass(Tbl4.class).
Probably you are missing .hbm files in case of loading via configuration file(xml file). Try adding hbm files for each table.
i think you are missing hibernate.cfg.xml file. i mean if your cfg file name is different from hibernate.cfg.xml, then need to configure Configuration configuration = new Configuration(); configuration.configure("filename.cfg.xml"); .beacause hibernate by default takes hibernate.cfg.xml file without configuring in configuration.configure(); but if cfg file name is different then need to put it in configure(). your file need to place in src folder. if you place it in different place then need to pass it with correct path.

hibernate configuration file and SessionFactory

I am struggling at the moment to find out why I get this error messages.
I'm using hibernate for the first time so that I could have configured something wrong.
IMO it could be one of this 3 problems.
My hibernate.cfg.xml file is at the wrong "place" but I didn't change the classpath and the hibernet file is inside the src folder.
I get a warning at the line where I create a new SessionFactory SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
There are 2 types which i can get back from buildSessionFactory()
SessionFactory
Configuration
Of course I took SessionFactory but maybe I overlook something.
package hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import persistencelayer.*;
public class HibernateTest {
public static void main(String[] args) {
TestUserDetails user2 = new TestUserDetails();
user2.setUserId(1);
user2.setUserName("First User");
user2.setAddress("First User's address");
user2.setJoinedDate(new Date());
user2.setDescription("Description of the user goes here");
try {
//SessionFactory wird erzeugt, mit der Konfiguration von Hibernate
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
// session.save(user);
session.save(user2);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Fehler beim erstellen der SessionFactory");
}
}
}
`
It could also be that i configured my hibernate.cfg.xml file wrong. I am deleting the username, password and host, for safety reasons.
I am trying to find the solution since google but it is simply not working.
I am using Oracle as DB btw.
Suggestions would be appreciated. Thank you in advance and sorry for the long post :).
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#host:port:ssid:</property>
<property name="hibernate.connection.username">name</property>
<property name="hibernate.connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<!-- Disable the second-level cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="persistencelayer.Project"/>
<mapping class="persistencelayer.User"/>
<!-- <mapping class="persistencelayer.Employer"/>
<mapping class="persistencelayer.IndividualTest"/>
<mapping class="persistencelayer.ObjectType"/>
<mapping class="persistencelayer.TestChamber"/>
<mapping class="persistencelayer.TestMethod"/>
<mapping class="persistencelayer.TestUserDetails"/> -->
</session-factory>
i have found the problem it is inside the hibernate.cfg.xml file.
i copied it from the offical hibernate 4.3.9 files.
This section is wrong.
<property name="hibernate.connection.password" />password</property>
there should not be a "/" on the left side where password is meant to be put in.

How to use WebLogic configured connection pool (with JNDI Name) in Spring Hibernate Oracle DB

I'm fairly new at this and I'm stuck. If someone could help, that would be great.
My code right now uses inbuilt connection pool, how to change to Weblogic configured connection pool ? My code right now is as below:
hibernate-cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="hibernate.connection.release_mode">after_transaction</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Configure BLOB/CLOB settings in hibernate -->
<property name="hibernate.connection.SetBigStringTryClob">true</property>
<property name="hibernate.jdbc.batch_size">0</property>
<!--Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="cache.use_query_cache">false</property>
<property name="cache.use_minimal_puts">false</property>
<property name="max_fetch_depth">3</property>
<!-- Bind the getCurrentSession() method to the thread. -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Hibernate Session Class that has the getSession method:
public class HibernateSession {
public Session getSession() {
Configuration configuration = new AnnotationConfiguration();
configuration.setProperty("hibernate.connection.username", USERNAME);
configuration.setProperty("hibernate.connection.password", PASSWORD);
configuration.setProperty("hibernate.connection.url", DB_URL);
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
return session;
}
}
Hibernate version: 4.2.11.Final
Weblogic: 10.3.6
You need to use JNDI lookup to look up the datasource you configured via WebLogic Admin console.

Categories