I have been reading the book 'Java Persistence with Hibernate' and downloaded the source code. I am able to run the 'helloworld-native' files with XML mapping, but cannot run the annotated version of those files. Could anyone tell me if they had difficulty with that section or could they point it out step by step please?
The section I cannot pass is 2.2.1 Using Hibernate Annotations
When running 'ant schemaexport' I receive the following error message:
org.hibernate.HibernateException: The dialect was not set. Set the property hibernate dialect.
Which I shouldn't have to do in the XML file as the book does not say to do so. I do it anyway and get the following message....
UserSuppliedConnectionProvider:23 - No connection properties specified - the user must supply the JDBC connection
In HibernateUtil I have tried both...
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
sessionFactory = new Configuration().configure().buildSessionFactory();
Hibernate.cfg
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- ... Many property settings ... -->
<!-- List of annotated classes-->
<mapping class="hello.Message"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package persistence;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.cfg.AnnotationConfiguration;
/**
* Startup Hibernate and provide access to the singleton SessionFactory
*/
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
// Alternatively, we could look up in JNDI here
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Message.java
package hello;
import javax.persistence.*;
#Entity
#Table(name = "MESSAGES")
public class Message {
#Id #GeneratedValue
#Column(name = "MESSAGE_ID")
private Long id;
#Column(name = "MESSAGE_TEXT")
private String text;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "NEXT_MESSAGE_ID")
private Message nextMessage;
private Message() {}
public Message(String text) {
this.text = text;
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Message getNextMessage() {
return nextMessage;
}
public void setNextMessage(Message nextMessage) {
this.nextMessage = nextMessage;
}
}
HelloWorld.java
package hello;
import org.hibernate.*;
import persistence.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
// ############################################################################
// First unit of work
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message("Hello World");
session.save(message);
tx.commit();
session.close();
// ############################################################################
// Second unit of work
Session secondSession = HibernateUtil.getSessionFactory().openSession();
Transaction secondTransaction = secondSession.beginTransaction();
List messages =
secondSession.createQuery("from Message m order by m.text asc").list();
System.out.println( messages.size() + " message(s) found:" );
for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}
secondTransaction.commit();
secondSession.close();
// ############################################################################
// Third unit of work
Session thirdSession = HibernateUtil.getSessionFactory().openSession();
Transaction thirdTransaction = thirdSession.beginTransaction();
// message.getId() holds the identifier value of the first message
Message loadedMessage = (Message) thirdSession.get( Message.class, message.getId());
loadedMessage.setText( "Greetings Earthling" );
loadedMessage.setNextMessage(
new Message( "Take me to your leader (please)" )
);
thirdTransaction.commit();
thirdSession.close();
// ############################################################################
// Final unit of work (just repeat the query)
// TODO: You can move this query into the thirdSession before the commit, makes more sense!
Session fourthSession = HibernateUtil.getSessionFactory().openSession();
Transaction fourthTransaction = fourthSession.beginTransaction();
messages =
fourthSession.createQuery("from Message m order by m.text asc").list();
System.out.println( messages.size() + " message(s) found:" );
for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}
fourthTransaction.commit();
fourthSession.close();
// Shutting down the application
HibernateUtil.shutdown();
}
}
Related
SOLVED
The error I made was in the ConnectionUtils class, basically I was configuring hibernate without adding classes.
For anyone habing this problem I will leave new ConnectionUtils class.
PROGRAM INFO
Hi, I'm new to Hibernate framework and I'm developing a simple program that manages an Hostel.
I've made and populated a mySQL database called 'hostel_db' and I want to build a java desktop application
that enables me to interact with the database.
QUERY PROBLEM
I have done some research on how to setup and connect to a database with Hibernate, now I am trying to make a simple query on it to show elements in a table, but I get "QuerySyntaxException: Class is not mapped" as output.
Apparently the connection is done successfully but for some reason I can't figure out where I'm failing.
This is what the program (part of it) looks like:
PS: the connection details (username, password, etc. are done with a ConnectionUtils class).
mySQL DATABASE
CREATE TABLE hostel (
hid VARCHAR(10) PRIMARY KEY,
rooms INT NOT NULL,
profit INT DEFAULT 0,
cost INT DEFAULT 0
);
hibernate.cfg.xml
<?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>
<!--Use Hibernate's own connection pool configuration-->
<property name="connection.url">jdbc:mysql://localhost:3306/hostel_db</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--hibernate dialect-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!--Print sql statement-->
<property name="hibernate.show_sql">false</property>
<!--Format sql-->
<property name="hibernate.format_sql">true</property>
<!-- Load map file -->
<mapping resource="com/hostelmanagment/tables/config/Employee.hbm.xml"/>
<mapping resource="com/hostelmanagment/tables/config/Student.hbm.xml"/>
<mapping resource="com/hostelmanagment/tables/config/Hostel.hbm.xml"/>
</session-factory>
</hibernate-configuration>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="com.hostelmanagment.tables">
</persistence-unit>
</persistence>
Hostel
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table (name = "hostel")
public class Hostel implements Serializable {
// DATABASE ATTRIBUTES
#Id
#Column (name = "hid")
private String hid;
#Column (name = "rooms")
private int rooms;
#Column (name = "profit")
private int profit;
#Column (name = "cost")
private int cost;
// OTHER VARIABLES
// CONSTRUCTOR
public Hostel() {}
public Hostel(String hid, int rooms, int profit, int cost) {
this.hid = hid;
this.rooms = rooms;
this.profit = profit;
this.cost = cost;
}
// GETTERS
public int getRooms() {
return rooms;
}
public int getProfit() {
return profit;
}
public int getCost() {
return cost;
}
//
#Override
public String toString() {
return hid + " - Rooms: " + rooms + " - Profit: " + profit + " - Cost: " + cost;
}
}
hostel.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- name:full path to class:-->
<!-- table: table name: (can be omitted. Use the class name as the table name.)-->
<class name="com.hostelmanagment.tables.Hostel" table="hostel">
<!--Primary key-->
<id name="hid" column="hid">
<!--Primary key generation strategy-->
<generator class="native"></generator>
</id>
<property name="rooms" column="rooms" type="java.lang.Integer"/>
<property name="profit" column="profit" type="java.lang.Integer"/>
<property name="cost" column="cost" type="java.lang.Integer"/>
</class>
</hibernate-mapping>
Main
package com.hostelmanagment;
import com.hostelmanagment.gui.*;
import com.hostelmanagment.tables.Hostel;
import com.hostelmanagment.utils.*;
import javax.persistence.*;
import javax.persistence.Query;
import org.hibernate.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Connect to database
EntityManager em = ConnectionUtils.connectToDatabase(ConnectionData.getUsr(), ConnectionData.getPsw()).
createEntityManager();
Session session = ConnectionUtils.connectToDatabaseSession(ConnectionData.getUsr(), ConnectionData.getPsw()).
openSession();
// Test show data from databases
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from Hostel");
List<?> list = query.getResultList();
Hostel hostel = (Hostel) list.get(0);
System.out.println("\nHostel: \n" + hostel);
// Run GUI
//new HostelMainFrame(em);
}
}
ConnectionUtils
public class ConnectionUtils {
private static Map<String, String> databaseProperties = new HashMap<>();
private static Configuration databaseConfiguration = new Configuration();
private static final String dialect = "org.hibernate.dialect.MySQL5Dialect";
private static final String url = "jdbc:mysql://localhost:3306/hostel_db";
private static final String driver = "com.mysql.jdbc.Driver";
public static EntityManagerFactory connectToDatabase(String username, String password) {
// Try to set up the configuration for hibernate.cfg
try {
databaseConfiguration.configure().
setProperty("hibernate.connection.username", username).
setProperty("hibernate.connection.password", password);
} catch (HibernateException e) {
if (verifyHibernateConfigXml())
throw new RuntimeException("Wrong format for hibernate.cfg.xml");
}
// Build configurations
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().
applySettings(databaseConfiguration.getProperties());
SessionFactory factory = databaseConfiguration.buildSessionFactory(ssrb.build());
// Setup persistence
persistenceSetup(username, password);
// Return EntityManagerFactory
return Persistence.createEntityManagerFactory("com.hostelmanagment.tables", databaseProperties);
}
public static SessionFactory connectToDatabaseSession(String username, String password) {
// Try to set up the configuration for hibernate.cfg
try {
databaseConfiguration.configure().
setProperty("hibernate.connection.username", username).
setProperty("hibernate.connection.password", password);
} catch (HibernateException e) {
if (verifyHibernateConfigXml())
throw new RuntimeException("Wrong format for hibernate.cfg.xml");
}
// Build configurations
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().
applySettings(databaseConfiguration.getProperties());
// Setup persistence
persistenceSetup(username, password);
return databaseConfiguration.buildSessionFactory(ssrb.build());
}
private static boolean verifyHibernateConfigXml() {
try {
InputStream is = ConnectionUtils.class.getClassLoader().getResourceAsStream("hibernate.cfg.xml");
return true;
} catch (NullPointerException npe) {
throw new RuntimeException("hibernate.cfg.xml don't exists");
}
}
private static void persistenceSetup(String username, String password) {
databaseProperties.put("hibernate.connection.driver_class", driver);
databaseProperties.put("hibernate.connection.url", url);
databaseProperties.put("hibernate.connection.autocommit", "false");
databaseProperties.put("hibernate.connection.username", username);
databaseProperties.put("hibernate.connection.password", password);
databaseProperties.put("hibernate.dialect", dialect);
databaseProperties.put("hibernate.connection.CharSet", "utf8");
databaseProperties.put("hibernate.connection.characterEncoding", "utf8");
databaseProperties.put("hibernate.connection.useUnicode", "true");
databaseProperties.put("hibernate.show_sql", "true");
databaseProperties.put("hibernate.hbm2ddl.auto", "update");
}
}
FOLDER STRUCTURE
STACK TRACE
NEW CONNECTION UTILS
public class ConnectionUtils {
private static Map<String, String> databaseProperties = new HashMap<>();
private static Configuration databaseConfiguration = new Configuration();
private static final String dialect = "org.hibernate.dialect.MySQL5Dialect";
private static final String url = "jdbc:mysql://localhost:3306/".concat(ConnectionData.getDbName());
private static final String driver = "com.mysql.cj.jdbc.Driver";
private static EntityManagerFactory emf;
private static SessionFactory sessionFactory;
public ConnectionUtils(){}
public void setUpProperties() {
propertiesSetup(ConnectionData.getUsr(), ConnectionData.getPsw());
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder().
applySettings(databaseConfiguration.getProperties());
//standardServiceRegistryBuilder.configure();
emf = Persistence.createEntityManagerFactory(ConnectionData.getTablesPackage(), databaseProperties);
sessionFactory = databaseConfiguration.buildSessionFactory(standardServiceRegistryBuilder.build());
}
public EntityManagerFactory getEntityManagerFactory() {
return emf;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
private static void propertiesSetup(String username, String password) {
// Try to set up the configuration for hibernate.cfg
try {
databaseConfiguration.configure().
setProperty("hibernate.connection.username", username).
setProperty("hibernate.connection.password", password);
} catch (HibernateException e) {
if (verifyHibernateConfigXml())
throw new RuntimeException("Wrong format for hibernate.cfg.xml");
}
// Setup persistence
persistenceSetup(username, password);
}
private static boolean verifyHibernateConfigXml() {
try {
InputStream is = ConnectionUtils.class.getClassLoader().getResourceAsStream("hibernate.cfg.xml");
return true;
} catch (NullPointerException npe) {
throw new RuntimeException("hibernate.cfg.xml don't exists");
}
}
private static void persistenceSetup(String username, String password) {
try {
for (Class cls : getEntityClassesFromPackage(ConnectionData.getTablesPackage())) {
databaseConfiguration.addAnnotatedClass(cls);
}
} catch (Exception ex) { ex.printStackTrace(); }
databaseProperties.put("hibernate.connection.driver_class", driver);
databaseProperties.put("hibernate.connection.url", url);
databaseProperties.put("hibernate.connection.autocommit", "false");
databaseProperties.put("hibernate.connection.username", username);
databaseProperties.put("hibernate.connection.password", password);
databaseProperties.put("hibernate.dialect", dialect);
databaseProperties.put("hibernate.connection.CharSet", "utf8");
databaseProperties.put("hibernate.connection.characterEncoding", "utf8");
databaseProperties.put("hibernate.connection.useUnicode", "true");
databaseProperties.put("hibernate.show_sql", "true");
databaseProperties.put("hibernate.hbm2ddl.auto", "update");
}
private static List<Class<?>> getEntityClassesFromPackage(String packageName) throws ClassNotFoundException, URISyntaxException {
List<String> classNames = getClassNamesFromPackage(packageName);
List<Class<?>> classes = new ArrayList<Class<?>>();
for (String className : classNames) {
Class<?> cls = Class.forName(packageName + "." + className);
Annotation[] annotations = cls.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(cls.getCanonicalName() + ": " + annotation.toString());
if (annotation instanceof javax.persistence.Entity) {
classes.add(cls);
}
}
}
return classes;
}
private static ArrayList<String> getClassNamesFromPackage(String packageName) throws URISyntaxException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ArrayList<String> names = new ArrayList<String>();
packageName = packageName.replace(".", "/");
URL packageURL = classLoader.getResource(packageName);
URI uri = new URI(packageURL.toString());
File folder = new File(uri.getPath());
File[] files = folder.listFiles();
for (File file: files) {
String name = file.getName();
name = name.substring(0, name.lastIndexOf('.')); // remove ".class"
names.add(name);
}
return names;
}
}
Am trying to configure HibernateSearch for ElasticSearch Integration.
I have Product table in my oracle database. From that table am trying to search based on product name.
For that am trying to integrate HibernateSearch (ElasticSearch) along with oracle database.
Am getting the below error from HibernateSearch :
Am using Oracle database and added the required dependencies in my pom.xml file
Exception in thread "main" java.lang.IllegalArgumentException: java.lang.Object is not an indexed entity or a subclass of an indexed entity
at org.hibernate.search.batchindexing.impl.MassIndexerImpl.toRootEntities(MassIndexerImpl.java:87)
at org.hibernate.search.batchindexing.impl.MassIndexerImpl.<init>(MassIndexerImpl.java:63)
at org.hibernate.search.batchindexing.impl.DefaultMassIndexerFactory.createMassIndexer(DefaultMassIndexerFactory.java:33)
at org.hibernate.search.impl.FullTextSessionImpl.createIndexer(FullTextSessionImpl.java:175)
at com.test.webservice.elasticsearch.App.doIndex(App.java:36)
at com.test.webservice.elasticsearch.App.main(App.java:109)
Am using all the latest dependencies.
hibernate-search-orm ->5.9.1.Final
hibernate-core ->5.2.16.Final`
ojdbc14 -> 10.2.0.4.0
App.java
public class App
{
private static void doIndex() throws InterruptedException {
Session session = HibernateUtil.getSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait(); // Error occuring on this line
fullTextSession.close();
}
private static List<Product> search(String queryString) {
Session session = HibernateUtil.getSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("name").matching(queryString).createQuery();
// wrap Lucene query in a javax.persistence.Query
org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Product.class);
List<Product> productList = fullTextQuery.list();
fullTextSession.close();
return productList;
}
private static void displayContactTableData() {
Session session = null;
PropertiesFile propertiesFile= PropertiesFile.getInstance();
String driverClass = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.driver_class");
String connectionURL = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.url");
String userName = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.username");
String password = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.password");
String dialect = propertiesFile.extractPropertiesFile().getProperty("hibernate.dialect");
String showSQL = propertiesFile.extractPropertiesFile().getProperty("hibernate.show_sql");
try {
//session = HibernateUtil.getSession();
// Fetching saved data
String hql = "from Product";
#SuppressWarnings("unchecked")
Configuration cfg=new Configuration()
.setProperty("hibernate.connection.driver_class", driverClass)
.setProperty("hibernate.connection.url", connectionURL)
.setProperty("hibernate.connection.username", userName)
.setProperty("hibernate.connection.password", password)
.setProperty("hibernate.dialect", dialect)
.setProperty("hibernate.show_sql", showSQL)
.addAnnotatedClass(com.test.webservice.model.Product.class);
SessionFactory factory=cfg.buildSessionFactory();
session=factory.openSession();
Transaction t=session.beginTransaction();
List<Product> productList = session.createQuery(hql).list();
for (Product product : productList) {
System.out.println("Product Name --->"+product.getName());
}
} catch(HibernateException exception){
System.out.println("Problem creating session factory");
exception.printStackTrace();
}finally{
if(session != null) {
session.close();
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("\n\n******Data stored in Contact table******\n");
displayContactTableData();
// Create an initial Lucene index for the data already present in the database
doIndex(); // Error occuring on this line
Scanner scanner = new Scanner(System.in);
String consoleInput = null;
while (true) {
// Prompt the user to enter query string
System.out.println("\n\nEnter search key (To exit type 'X')");
System.out.println();
consoleInput = scanner.nextLine();
if("X".equalsIgnoreCase(consoleInput)) {
System.out.println("End");
System.exit(0);
}
List<Product> result = search(consoleInput);
System.out.println("\n\n>>>>>>Record found for '" + consoleInput + "'");
for (Product product : result) {
System.out.println(product);
}
}
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">vb</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.search.default.directory_provider">filesystem</property>
<property name="hibernate.search.default.indexBase">C:\lucene\indexes</property>
<mapping class="com.test.webservice.model.Product" />
</session-factory>
</hibernate-configuration>
Product.java
#Entity
#Indexed
#Table(name = "PRODUCT")
public class Product {
private String name;
private long id;
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setId(long id) {
this.id = id;
}
#Id
public long getId() {
return id;
}
}
The error message is wrong, it should be "java.lang.Object is not an indexed entity or a superclass of an indexed entity". I created a ticket, we'll fix the error message ASAP.
Regarding your problem, this exception means neither Object nor any of its subclasses is indexed. In short, there isn't any indexed class.
I can see that your Product class is annotated with #Indexed, so this probably means there is a problem with how you start Hibernate ORM in HibernateUtil.
The simple fact that you commented your line session = HibernateUtil.getSession(); in displayContactTableData() makes me think you already knew that, though.
You should have a look at the getting started guide to make sure you start Hibernate ORM correctly.
I had the same problem and I changed my import from import org.springframework.stereotype.Indexed; to import org.hibernate.search.annotations.Indexed; and it worked!!
I'm trying to use sqlite using hibernate. However, I've had hard time, configuring sqlite database path. Currently, my hibernate.cfg.xml looks like this:
<?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.url">jdbc:sqlite:test.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.test.entity.Category"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
I'm using IntelliJ. I've placed test.db in resources & in the artifacts I could see it in classes package. However, everytime I get this error:
org.hibernate.hql.internal.ast.QuerySyntaxException: Category is not mapped [select id from Category]
Category.java
#Entity
#Table(name = "category", schema = "", catalog = "")
public class Category {
private String id;
private String name;
private String imageUrl;
#Id
#Column(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "imageUrl")
public String getImageUrl() {
return imageUrl;
}
}
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null){
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
I'm using Hibernate version 5.1.0
I've checked sessionFactory.getAllClassMetadata() - it shows no class mapped. Any help would be greatly appreciated.
You use an incorrect way of Hibernate 5 configuration.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
In Hibernate 5, when you do configuration.configure("hibernate.cfg.xml") everything is configured properly. But when you do configuration.buildSessionFactory(serviceRegistry) all configuration is lost.
Just do
return new Configuration().configure().buildSessionFactory();
Refer
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
I am new at Hibernate Annotations and I'd like to try an example.
I have two classes (Node and HyperEdge), when I run my application, it only creates a table for Node and not for HyperEdge.
This is the code I developed:
Node :
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Node")
public class Node {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column
private String name;
#Column(name="\"group\"")
private Integer group;
public Node() {
super();
// TODO Auto-generated constructor stub
}
public Node(Integer id, String name, Integer group) {
super();
this.id = id;
this.name = name;
this.group = group;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGroup() {
return group;
}
public void setGroup(Integer group) {
this.group = group;
}
}
HyperEdge :
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Table(name="HyperEdge")
public class HyperEdge {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column
private String title;
public HyperEdge() {
super();
// TODO Auto-generated constructor stub
}
public HyperEdge(Integer id, String title) {
super();
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
hibernate.cfg.xml :
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/exhiber</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.hib.ex.entity.Node" />
<mapping class="com.hib.ex.entity.HyperEdge" />
</session-factory>
</hibernate-configuration>
HibernateDao :
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hib.ex.entity.HyperEdge;
import com.hib.ex.entity.Node;
public class HibExDao {
public void saveNode(Node noeud) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(noeud);
session.getTransaction().commit();
session.close();
}
public List listNode() {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
List nodes = session.createQuery("FROM Node").list();
session.close();
return nodes;
}
public Node readNode(Integer id) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
Node noeud = (Node) session.get(Node.class, id);
session.close();
return noeud;
}
public void saveHyperEdge(HyperEdge he, String chaine) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
he.setTitle(chaine);
session.save(he);
session.getTransaction().commit();
session.close();
}
public List listHyperEdge() {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
List hyperedges = session.createQuery("FROM HyperEdge").list();
session.close();
return hyperedges;
}
public HyperEdge readHyperEdge(Integer id) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
HyperEdge hyperEdge = (HyperEdge) session.get(HyperEdge.class, id);
session.close();
return hyperEdge;
}
}
The main class :
import java.util.List;
import com.hib.ex.dao.HibExDao;
import com.hib.ex.entity.HyperEdge;
import com.hib.ex.entity.Node;
public class Run {
public static void main(String[] args) {
HibExDao dao = new HibExDao();
System.out.println("****************WRITING****************");
Node n1 = new Node();
n1.setName("toto");
dao.saveNode(n1);
System.out.println("Node saved!");
Node n2 = new Node();
n2.setName("lala");
dao.saveNode(n2);
System.out.println("Node saved!");
System.out.println("\n****************READING****************");
List nodes = dao.listNode();
System.out.println("Name in Node number 2 is: " + dao.readNode(2).getName());
}
}
What is the problem? And how can I fix it?
Thanks!
Perhaps you have to add #Entity annotation to your HyperEdge class
#Entity annotation to missing from your HyperEdge class
The #Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
The #Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If #Table annotation is not specified then Hibernate will by default use the class name as the table name.
In HyperEdge class you have to add #Entity annotation so that hibernate can treat it as a entity to map with table HyperEdge in database.
#Entity
#Table(name="HyperEdge")
public class HyperEdge {
I am new to hibernate and I have stupid problem. My files:
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:postgresql://localhost/booktown
</property>
<property name="hibernate.connection.username">
mirek
</property>
<mapping resource="Books.hbm.xml"/>
</session-factory>
</hibernate-configuration>
books.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Books" table="books">
<meta attribute="Książki w booktown">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="title" column="title" type="string"/>
<property name="author_id" column="author_id" type="int"/>
<property name="subject_id" column="subject_id" type="int"/>
</class>
</hibernate-mapping>
Books.java
public class Books
{
private int id;
private String title;
private int author_id;
private int subject_id;
public Books(String title, int author_id, int subject_id)
{
this.title = title;
this.author_id = author_id;
this.subject_id = subject_id;
}
public void setId(int id)
{
this.id = id;
}
public void setTitle(String title)
{
this.title = title;
}
public void setAuthorId(int author_id)
{
this.author_id = author_id;
}
public void setSubjectId(int subject_id)
{
this.subject_id = subject_id;
}
public int getId()
{
return id;
}
public String getTitle()
{
return title;
}
public int getAuthorId()
{
return author_id;
}
public int getSubjectId()
{
return subject_id;
}
}
and Booktown.java
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Booktown
{
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args)
{
try
{
//private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
//return factory;
//factory = new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object." + ex.toString());
throw new ExceptionInInitializerError(ex);
}
Booktown BT = new Booktown();
/* Add few employee records in database */
Integer bID1 = BT.addBook(10, "Jakiś napis", 10, 30);
Integer bID2 = BT.addBook(20, "Jakiś inny napis", 10, 50);
//Integer bID3 = BT.addBook(30, "John", 10000, 14);
/* List down all the employees */
BT.listBooks();
/* Update employee's records */
BT.updateBook(bID1, 5000);
/* Delete an employee from the database */
BT.deleteBook(bID2);
/* List down new list of the employees */
BT.listBooks();
}
/* Method to CREATE a book in the database */
public Integer addBook(int bid, String fname, int lname, int salary)
{
Session session = factory.openSession();
Transaction tx = null;
Integer bID = null;
try
{
tx = session.beginTransaction();
Books book = new Books(fname, lname, salary);
bid = (Integer) session.save(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
return bID;
}
/* Method to READ all the books */
public void listBooks()
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
List<Books> books = session.createQuery("FROM books").list();
for (Iterator<Books> iterator = books.iterator(); iterator.hasNext();)
{
Books book = (Books) iterator.next();
System.out.print("First Name: " + book.getTitle());
System.out.print(" Last Name: " + book.getAuthorId());
System.out.println(" Salary: " + book.getSubjectId());
}
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to UPDATE author for a book */
public void updateBook(Integer bID, int auth)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Books book = (Books) session.get(Books.class, bID);
book.setAuthorId(auth);
session.update(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to DELETE a book from the records */
public void deleteBook(Integer bID)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Books book = (Books) session.get(Books.class, bID);
session.delete(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
}
Code is compiling but at run I get:
> paź 15, 2013 8:44:38 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Failed to create sessionFactory object.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "main" java.lang.ExceptionInInitializerError
at Booktown.main(Booktown.java:34)
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:385)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
at Booktown.main(Booktown.java:25)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
... 4 more
Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135)
... 13 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for author_id in class Books
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:316)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:310)
at org.hibernate.mapping.Property.getGetter(Property.java:321)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:444)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:200)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
... 18 more
I found similar problem there was no setter. In my case system says that there is no getter for author_id but it is at line 45 in Books.java.
Could sb tells me what is wrong? Maybe there is an other cause which I don't see...
public int getAuthorId()
{
return author_id;
}
should be (observe, author_id)
public int getAuthor_id()
{
return author_id;
}
OR update XML as #Boris the spider commented.
As far as I know Hibernate requires a no-arg constructor which your Books class does seem to have. So even if you get the save part working I think your code will fail when you attempt to load.
Thus, create a constructor:
public Books(){
}
Why does Hibernate require no argument constructor?
Also, as pointed out previously ditch the XML and use JPA annotations. In line with standard Java conventions rename Books to Book and remove the _ from your variable names.
Alan
I had once this problem and I fix it like that:
You should Generate Constructor, Getters and Setters in NetBeans IDE ( I'm working with IDE is netbeans) so you have to press shortcut ALT+Insert (CTLRL+I on Mac). After invoking the shortcut, all possible generators are offered.