Unable to insert data into database properly using Hibernate - java

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.

Related

(SOLVED) Java Hibernate - QuerySyntaxException: Class is not mapped

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;
}
}

Inserting a row into a database using hibernate, I'm getting "1" and null put into the database instead of user inputted values

I am trying to add a row to the database using hibernate and sessions/sessionfactory. However when I did the following code, it only added to the database once with values of "1, null". I think the problem is within ProductAdd.java (below), but I am not sure.
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.product.Product;
import com.utility.HibernateUtility;
#WebServlet("/ProductAdd")
public class ProductAdd extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("inside servlet");
Product product= new Product(request.getParameter("prodId"),request.getParameter("prodName"));
try {
Product p = new Product();
p.setName(product.getName());
p.setId(product.getName());
Session session = HibernateUtility.getSessionFactory().openSession();
org.hibernate.Transaction transaction = null;
try {
transaction = session.beginTransaction();
String sql = "INSERT INTO Product VALUES (:idVal, :nameVal)";
Query query = session.createSQLQuery(sql);
query.setParameter("idVal", product.getId());
query.setParameter("nameVal", product.getName());
query.executeUpdate();
session.getTransaction().commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
System.out.println(("Product is added."));
} catch (Exception e) {
// TODO: handle exception
}
HttpSession session= request.getSession();
session.setAttribute("sesname", request.getParameter("prodId"));
response.sendRedirect("addsuccess.jsp");
}
}
Here is my Product.java if needed also:
package com.product;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Product implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private String name;
public Product(String string, String string2) {
super();
// TODO Auto-generated constructor stub
}
public Product() {
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I also have my HibernateUtility class:
package com.utility;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtility {
private static final SessionFactory sessionFactory = createSessionFactory();
public static SessionFactory createSessionFactory() {
try {
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Exception ex) {
System.err.println("SessionFactory creation failed");
throw new ExceptionInInitializerError(ex);
}
}
/**
* #return the sessionfactory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Along with hibernate.cfg.xml.
You are not actually using the request parameters because your product constructor looks like this:
public Product(String string, String string2) {
super();
// TODO Auto-generated constructor stub
}
So this line doesn't do what you expect:
Product product= new Product(request.getParameter("prodId"),request.getParameter("prodName"));
And neither do these:
Product p = new Product();
p.setName(product.getName());
p.setId(product.getName());
or these:
query.setParameter("idVal", product.getId());
query.setParameter("nameVal", product.getName());
(by the way, not sure what is the use of p if you still use product to set the query params).
So you end up with null for the product name, and 1 for the id because of the GenerationType.AUTO, otherwise that would have been null too, I think.
You need to change your constructor to use the parameters:
public Product(String string, String string2) {
this.id = string;
this.name = string2;
}
This way, you will later have something to send to your database query.

upgrading from Hiberante 3 to Hibernate 4 can't persist data to datatbase

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";
}
}

hibernate doesn't see a setter

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.

Hibernate and constraints primary key throws a QueryException

Using oracle DB, we created a table without PK (we are aware that its not a good practice, but we are still hoping that someone can help us) and we need to use a constraint as an alternative. We able to insert data to the DB, unfortunately we can't retrieve because it throws an exception.
Exception in thread "main" org.hibernate.QueryException: could not resolve property: name of: hibernate.Person [FROM hibernate.Person WHERE name = :name AND nickname= :nickname]
hibernate-mapping
<hibernate-mapping>
<class name="com.sample.Person" table="PERSONS" schema="person_schema">
<composite-id name="id" >
<key-property name="name" column="NAME" />
<key-property name="nickname" column="NICKNAME" />
</composite-id>
<property name="address" type="java.lang.String">
<column name="ADDRESS" length="100" />
</property>
</class>
</hibernate-mapping>
PersonDao.java
package hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class PersonDAO extends BaseHibernateDAO {
public List<Person> getAll(Person person) {
try {
Query query = getSession().createQuery("FROM PERSONS " +
"WHERE name = :name " +
"AND nickname = :nickname");
query.setString("name", person.getName());
query.setString("nickname", person.getNickname());
List<Person> persons =(List)query.list();
return persons;
} catch (RuntimeException re) {
System.out.println("get failed");
throw re;
}finally{
getSession().close();
}
}
public void save(Person person) {
try {
Transaction tx = getSession().beginTransaction();
getSession().save(person);
tx.commit();
} ...
}
}
PersonId.java
package hibernate;
import java.io.Serializable;
public class PersonId implements Serializable {
private String name;
private String nickname;
private String address;
// getters & setters .....
// an easy initializing constructor
public PersonId(String name, String nickname, String address){
this.name = name;
this.nickname = nickname;
this.address = address;
}
#Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof PersonId)) return false;
PersonId arg1 = (PersonId) arg0;
return (this.name.equalsIgnoreCase(arg1.getName())
&& (this.nickname.equalsIgnoreCase(arg1.getNickname()))
&& (this.address.equalsIgnoreCase(arg1.getAddress()))
);
}
#Override
public int hashCode() {
int hsCode;
hsCode = name.hashCode();
hsCode = hsCode + nickname.hashCode();
hsCode = 19 * hsCode + address.hashCode();
return hsCode;
}
}
Person.java
package hibernate;
public class Person {
private PersonId id;
private String name;
private String nickname;
private String address;
//getters and setters ...
}
TestHibernate.java
package test;
import hibernate.Person;
import hibernate.PersonId;
import hibernate.PersonDAO;
import java.util.Iterator;
public abstract class TestHibernate {
public static void main(String[] args) throws InterruptedException {
/*
Person p = new Person();
p.setPersonId(new PersonId("Foor", "Foo", "Sample Address"));
p.setName("Foor");
p.setNickname("Foo");
p.setAddress("Sample Address");
p.setValue("0");
PersonDao dao = new PersonDao();
//dao.save(p);
*/
Person p = new Person();
p.setName("Foor");
p.setNickname("Foo");
PersonDao dao = new PersonDao();
dao.getAll(p);
}
}
Thanks in advance!
A SELECT is missing at the beginning of the query.
And when calling createQuery() you must use JPQL/HQL. So either modify your query to make it HQL (using entity classes names etc...), or use createSQLQuery() instead.
I can see some problems here ( I may be wrong, correct me if I do) -
Query query = getSession().createQuery("FROM PERSONS " +
"WHERE name = :name " +
"AND nickname = :nickname");
Since, you are using HQL,
PERSON should be Person, the property Class name.
Check this link for an explanation.
Thanks

Categories