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;
}
}
Related
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 started using the Hibernate recently. I am facing the below problem
Description: For the object customer, when I try to insert the data into database using hibernate saveOrUpdate it is deleting all the entries in the customer table and inserting only the new row with the new data. I am unable to figure out what is causing the problem. If try to insert another data same time by adding new Customer object (namely customer1) with different unique CODE after session.saveOrUpdate(customer), I am getting identifier already exists exception.
Definition of the table in database is as below
create table customer(
code varchar(100) not null,
name varchar(100) not null,
address varchar(1000) not null,
phone1 varchar(100) not null,
phone2 varchar(100),
credit_limit double default 0,
current_credit double default 0,
primary key ( code )
);
Java object defined is as below
package com.jwt.hibernate.bean;
import java.io.Serializable;
public class Customer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2590997804699225005L;
private String code;
private String name;
private String address;
private String phone1;
private String phone2;
private Double creditLimit;
private Double currentCredit;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
public Double getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(Double creditLimit) {
this.creditLimit = creditLimit;
}
public Double getCurrentCredit() {
return currentCredit;
}
public void setCurrentCredit(Double currentCredit) {
this.currentCredit = currentCredit;
}
}
Class that is performing the hibernate action is as below
package com.jwt.hibernate.dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.jwt.hibernate.bean.Customer;
public class CustomerDAO {
public boolean save(Customer customer){
try{
// 1. configuring hibernate
Configuration configuration = new Configuration().configure();
// 2. create sessionfactory
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 3. Get Session object
Session session = sessionFactory.openSession();
// 4. Starting Transaction
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(customer);
transaction.commit();
session.close();
sessionFactory.close();
} catch (HibernateException e) {
System.out.println(e.getMessage());
System.out.println("error");
}
finally{
}
return true;
}
}
Hibernate config xml is as below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.jwt.hibernate.bean.Customer" table="CUSTOMER">
<id column="CODE" name="code" type="java.lang.String" />
<property column="NAME" name="name" type="java.lang.String" />
<property column="ADDRESS" name="address" type="java.lang.String" />
<property column="PHONE1" name="phone1" type="java.lang.String" />
<property column="PHONE2" name="phone2" type="java.lang.String" />
<property column="CREDIT_LIMIT" name="creditLimit" type="java.lang.Double" />
<property column="CURRENT_LIMIT" name="currentCredit" type="java.lang.Double" />
</class>
</hibernate-mapping>
Servlet that is handling the request is as below
package com.jwt.hibernate.controller;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jwt.hibernate.bean.Customer;
import com.jwt.hibernate.dao.CustomerDAO;
public class CustomerControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ObjectInputStream in = new ObjectInputStream(request.getInputStream());
try {
Object object = (Object) in.readObject();
in.close();
String action = request.getParameter("action");
if(action!= null && action.equals("save")){
save(object, response);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void save(Object object, HttpServletResponse response) throws IOException{
Customer customer = (Customer) object;
try {
CustomerDAO customerDAO = new CustomerDAO();
customerDAO.save(customer);
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
oos.writeObject(customer);
oos.flush();
oos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Client side code that is sending the object to save to database is as below
public static Object save(Object object,int objectType)
{
URL url;
if(objectType == TYPE_CUSTOMER) {
Customer customer = (Customer) object;
try {
url = new URL("http://localhost:8080/CrossoverServer/Customer?action=save");
urlCon = (HttpURLConnection) url.openConnection();
urlCon.setDoOutput(true); // to be able to write.
urlCon.setDoInput(true); // to be able to read.
out = new ObjectOutputStream(urlCon.getOutputStream());
out.writeObject(customer);
out.close();
ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
customer = (Customer) ois.readObject();
ois.close();
return customer;
} catch (IOException e) {
e.printStackTrace();
}
catch ( ClassNotFoundException e2) {
e2.printStackTrace();
}
}
return null;
}
The way customer object created is as below
public Object guiToObject()
{
Customer customer = new Customer();
customer.setCode(txtCode.getText());
customer.setName(txtName.getText());
customer.setAddress(txtAddress.getText());
customer.setPhone1(txtPhone1.getText());
customer.setPhone2(txtPhone2.getText());
customer.setCreditLimit((Double) Double.parseDouble(txtCreditLimit.getText()));
if(txtCurrentCredit.getText() != null && !txtCurrentCredit.getText().trim().isEmpty())
customer.setCurrentCredit((Double) Double.parseDouble(txtCurrentCredit.getText().trim()));
else
customer.setCurrentCredit(0.0);
return customer;
}
Can some one please help me what is going wrong with the above approach of inserting new rows into customer table.
Thanks.
Possible reason could be your code recreating the tables, and adding record afterwords.
Have you tried debugging and looking at the database side to see what is happening before insert?
One side note; your finally block is blank. You should have your session closing and similar stuff coded inside finally block.
Thanks for he quick response.
I figured out the reason.
Changing the below property in hibernate.cfg.xml from "create" to "validate" resolved the problem.
validate
Thanks.
OK, we have an Hibernate 3 application that I am trying to update to hibernate 4. I can retrieve the data without any problem, but cannot add or update the database. I don't get any error messages, the transaction seems to work, but nothing gets changed in the database. Some help would be greatly appreciated.
Here's the config file 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>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.connection.datasource">jdbc/misc</property>
<property name="hibernate.jndi.url">iiop://127.0.0.1:3700</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
<property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.SunONETransactionManagerLookup</property>
<mapping resource="sponsor.hbm.xml"/>
<mapping resource="portfolio.hbm.xml"/>
<mapping resource="clientID.hbm.xml"/>
<mapping resource="legacyID.hbm.xml"/>
<mapping resource="badClient.hbm.xml"/>
<mapping resource="language.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Here's a sam;ole map file of the table I am currently working with sponsor.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>
<class name="com.lingosys.hibernate.Sponsor" table="sponsor">
<id name="companyID" type="integer">
<generator class="assigned"/>
</id>
<property name="companyName" type="string"/>
<property name="sponsorID" type="integer"/>
<property name="sponsorName" type="string"/>
<property name="status" type="string"/>
</class>
</hibernate-mapping>
Here's the class for creating the session factory HibenateUtil.java:
package com.lingosys.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* Hibernate Utility class with a convenient method to get Session Factory object.
*
* #author mphoenix
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Here's the dao file SponsorDAO.java:
package com.lingosys.hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
/**
*
* #author mphoenix
*/
public class SponsorDAO {
private Session session = null;
public SponsorDAO() {
}
private void startOperation() {
session = HibernateUtil.getSessionFactory().openSession();
}
public void create(Sponsor sponsor) {
startOperation();
session.saveOrUpdate("Sponsor", sponsor);
session.close();
}
public void update(Sponsor sponsor) {
startOperation();
session.update("Sponsor", sponsor);
session.close();
}
public Sponsor findSponsor(int id) {
startOperation();
Sponsor sponsor = (Sponsor) session.get(Sponsor.class, new Integer(id));
session.close();
return sponsor;
}
public List <Sponsor> findAllSponsors() {
List <Sponsor> sponsors = null;
startOperation();
Query query = session.createQuery("from Sponsor");
sponsors = query.list();
session.close();
return sponsors;
}
public void delete(Sponsor sponsor) {
startOperation();
session.delete(sponsor);
session.close();
}
}
Here's the create transaction code:
UserTransaction tx = null;
try {
tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
dao.create(sponsor);
tx.commit();
} catch (HibernateException ex) {
try {
tx.rollback();
} catch (Exception ex2) {
facesCtx.addMessage(null, new FacesMessage("Error on rollback.",
ex2.toString()));
}
facesCtx.addMessage(null, new FacesMessage("Hibernate Error.",
ex.toString()));
return null;
} catch (Exception ex) {
facesCtx.addMessage(null, new FacesMessage("Non-hibernate Error.",
ex.toString()));
return null;
}
Here's a retrieval transaction:
try {
tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
setSponsorItems(new ArrayList<Sponsor>());
List<Sponsor> sponsors = dao.findAllSponsors();
for (Sponsor aSponsor : sponsors) {
if (companyItemsMap.get(aSponsor.getCompanyID()) != null) {
getSponsorItems().add(aSponsor);
}
}
tx.commit();
} catch (HibernateException ex) {
try {
tx.rollback();
} catch (Exception ex2) {
facesCtx.addMessage(null, new FacesMessage(ex2.toString()));
}
facesCtx.addMessage(null, new FacesMessage(ex.toString()));
return false;
} catch (Exception ex) {
facesCtx.addMessage(null, new FacesMessage(ex.toString()));
return false;
}
And finally the object being mapped to Sponsor.java
package com.lingosys.hibernate;
import java.io.Serializable;
/**
*
* #author mphoenix
*/
public class Sponsor implements Serializable {
private int companyID;
private String companyName;
private int sponsorID;
private String sponsorName;
private String status;
public Sponsor() {
}
public int getCompanyID() {
return companyID;
}
public void setCompanyID(int companyID) {
this.companyID = companyID;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getSponsorID() {
return sponsorID;
}
public void setSponsorID(int sponsorID) {
this.sponsorID = sponsorID;
}
public String getSponsorName() {
return sponsorName;
}
public void setSponsorName(String sponsorName) {
this.sponsorName = sponsorName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Sponsor other = (Sponsor) obj;
if (this.companyID != other.companyID) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + this.companyID;
return hash;
}
//DEBUG CASPERW
#Override
public String toString() {
return "CompanyID: "+companyID+" CompanyName: "+companyName+" SponsorID: "+sponsorID+" SponsorName: "+sponsorName+"\n";
}
}
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();
}
}
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.