I am using Hibernate project in my eclipse with oracle database and java application.
after added new class(exist in my database) to my Hibernate project, and run my java project.it's loaded successfully also allow to add data from java project to hibernate table but at add these data to database i got this error
Unknown entity: com.se.automation.db.client.mapping.DocumentWRONGMODDATESTATUS
here is my code to add data to my database.
note ( I opened the session and i test it with another class exist in the same Hibernate project with the same structure to this class "Hibernate Project" )
DocumentWRONGMODDATESTATUS docstatus = new DocumentWRONGMODDATESTATUS();
docstatus.setOriginalDocId(doc.getPdf().getId());
at this moment every thing fine , but below line give the error(test it in debugging mode)
addDocumentWrongModDateStatus(docstatus ,Session );
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Enable Hibernate's automatic session context management -->
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="connection.autoReconnect">true</property>
<!-- <property name="show_sql">true</property> -->
<property name="show_sql">true</property>
<property name="format_sql">false</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<!-- auto commit -->
<property name="connection.autocommit">true</property>
<!-- configuration pool via c3p0 -->
<property name="c3p0.idleConnectionTestPeriod">1000</property>
<property name="c3p0.initialPoolSize">1</property>
<property name="c3p0.maxPoolSize">1</property>
<property name="c3p0.maxIdleTime">1</property>
<property name="c3p0.maxStatements">3</property>
<property name="c3p0.minPoolSize">1</property>
<mapping resource="com/se/automation/db/client/mapping/DocumentWRONGMODDATESTATUS.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareChangedFet.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareCode.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareComment.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareMethod.hbm.xml" />
</session-factory>
</hibernate-configuration>
DocumentWRONGMODDATESTATUS.hbm.xml
<?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.se.automation.db.client.mapping.DocumentWRONGMODDATESTATUS"
table="DOCUMENTWRONGMODDATESTATUS">
<id column="ID" length="33" name="id" type="long">
<generator class="assigned" />
</id>
<property name="Status" type="java.lang.String">
<column name="STATUS" />
</property>
<property name="OriginalDocId" type="java.lang.Long">
<column name="ORIGINALDOCID" />
</property>
<property name="RevDocId" type="java.lang.Long">
<column name="REVDOCID" />
</property>
</class>
</hibernate-mapping>
DocumentWRONGMODDATESTATUS.java
package com.se.automation.db.client.mapping;
import java.io.Serializable;
public class DocumentWRONGMODDATESTATUS implements Serializable
{
private static final long serialVersionUID = 1L;
private Long id;
private String Status;
private Long OriginalDocId;
private Long RevDocId;
public Long getOriginalDocId()
{
return OriginalDocId;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getStatus()
{
return Status;
}
public void setStatus(String status)
{
Status = status;
}
public void setOriginalDocId(Long originalDocId)
{
OriginalDocId = originalDocId;
}
public Long getRevDocId()
{
return RevDocId;
}
public void setRevDocId(Long revDocId)
{
RevDocId = revDocId;
}
{
}
}
Related
I am migrating entity mapping from an annotations app to hbm.xml
I error this error and not found the solution. Thanks
java.lang.Exception: Not an entity: class com.enterprise.package.user.domain.User
I have hibernate.cfg.xml in the resources folder, User.hbm.xml in one package and User.class in another
User.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="com.enterprise.package.role.domain.User" table="user">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="identity" />
</id>
<property name="username" column="username" type="java.lang.String" unique="true"/>
<property name="password" column="password" type="java.lang.String"/>
<many-to-one name="role" column="role_id" class="com.enterprise.package.role.domain.Role" not-null="true"/>
</class>
</hibernate-mapping>
User.class
public final class User {
private Long id;
private String username;
private String password;
private Role role;
public User() {
}
public User(Long id) {
this.id = id;
}
public User(Long id, String username, String password, Role role) {
this.id = id;
this.username = username;
this.password = password;
this.role = role;
}
...
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">**</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<mapping package="com/enterprise/package/user/infrastructure/persistence/hibernate/Role.hbm.xml"/>
<mapping package="com/enterprise/package/user/infrastructure/persistence/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I think the package of User class may be wrong in User.hbm.xml (we cant see in your snippet the package of this class)...
In User.hbm.xml instead of
com.enterprise.package.role.domain.User
may be
com.enterprise.package.user.domain.User.
I am new to this Hibernate framework and using Hibernate 3 just to start using this framework.
I have a small module that is executing a update query.
public void saveProduct(Product prod) {
String hql = "UPDATE Product set description = :description, price = :price,ctr=ctr+1 WHERE id = :id";
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("description", prod.getDescription());
query.setParameter("price", prod.getPrice());
query.setParameter("id", prod.getId());
logger.info(prod.toString());
int result = query.executeUpdate();
logger.info("Rows affected: " + result);
}
These are logs for this particular module and i have issue in this part hibernate is showing two different update queries one without column ctr and other one with column ctr or is it a normal behaviour:
May 23, 2016 5:55:37 PM com.mogae.dashboard.db.dao.ProductDaoImp saveProduct
INFO: Description: test311;Price: 1.7279999999999998
Hibernate:
update
products
set
description=?,
price=?
where
id=?
Hibernate:
update
products
set
description=?,
price=?,
ctr=ctr+1
where
id=?
May 23, 2016 5:55:37 PM com.mogae.dashboard.db.dao.ProductDaoImp saveProduct
INFO: Rows affected: 1
This is my xml configuration for DB connectivity:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- the parent application context definition for the springapp application -->
<aop:config>
<aop:advisor pointcut="execution(* *..ProductManager.*(..))" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<bean id="productDao" class="com.mogae.dashboard.db.dao.ProductDaoImp">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
</beans>
and this is my hibernate mapping file :
<?xml version="1.0"?>
<!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.mogae.dashboard.actions.domain.Product" table="products" lazy="false">
<id name="id" column="id" type="int">
<generator class="native">
<param name="sequence">products_id_seq</param>
</generator>
</id>
<property name="description" column="description" type="string" />
<property name="price" column="price" type="double" />
</class>
</hibernate-mapping>
and this is my entity (Product) class:
package com.mogae.dashboard.actions.domain;
import java.io.Serializable;
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Description: " + description + ";");
buffer.append("Price: " + price);
return buffer.toString();
}
private String description;
private Double price;
private int id;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Please help i have been searching for this issue on the google and various hibernate forums but haven't found one.
I am new to Hibernate so please guide me.
I have 2 entities Companies & Employees. One Company should have many employees.
Employees Hibernate Mapping File
<hibernate-mapping>
<class name="com.hibernate.demo.Employees" table="employees">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="empId" type="int" column="emp_id">
<generator class="native"/>
</id>
<property name="empCId" column="emp_cid" type="int"/>
<property name="empName" column="emp_name" type="string"/>
<property name="empContact" column="emp_contact" type="int"/>
</class>
</hibernate-mapping>
Companies Hibernate Mapping File
<hibernate-mapping>
<class name="com.hibernate.demo.Companies" table="companies" >
<meta attribute="class-description">
This class contains the companies detail.
</meta>
<id name="compId" type="int" column="comp_id">
<generator class="native"/>
</id>
<set name="employees" cascade="all" >
<key column="emp_cid"/>
<one-to-many class="com.hibernate.demo.Employees" />
</set>
<property name="compName" column="comp_name" type="string"/>
<property name="compCity" column="comp_city" type="string"/>
</class>
</hibernate-mapping>
Hibernate Configuration File
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedbdemo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">knowarth</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="employees.hbm.xml"/>
<mapping resource="companies.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Simple POJO Classes.
Employees.java
public class Employees {
public Employees(){}
private int empId;
private int empCId;
private String empName;
private int empContact;
//Getter & Setter
}
Companies.java
public class Companies {
public Companies(){}
private int compId;
private String compName;
private String compCity;
private Set<Employees> employees;
//Getter & Setter
}
I want to delete Company Record from the companies table and all the employees from that company should be deleted. But the problem I am facing is that Company Record is deleted by all the Employees Record relative to that Company aren't deleted.
Below is the Delete Code
public class CompanyDao {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Companies comp = new Companies();
Scanner compSc = new Scanner(System.in);
public void deleteComp(){
session.beginTransaction();
System.out.println("Enter Company ID to delete it");
int cmp_id = compSc.nextInt();
Companies company = new Companies();
company.setCompId(cmp_id);
session.delete(company);
session.getTransaction().commit();
return;
}
}
You can rely on the database for cascading the DELETE statement, in which case you need to change the mapping to:
<set name="employees" cascade="all" inverse="true" >
<key column="emp_cid" on-delete="cascade" />
<one-to-many class="com.hibernate.demo.Employees" />
</set>
If you don't want to change the mapping, you need to fetch the entity from the database and let Hibernate handle the children deletion:
public void deleteComp(){
session.beginTransaction();
System.out.println("Enter Company ID to delete it");
int cmp_id = compSc.nextInt();
Companies company = session.get(Companies.class, cmp_id);
session.delete(company);
session.getTransaction().commit();
return;
}
When I tried my first hibernate program and I got this error.
My program simply insert empID,first_name,second_name(table names) and using MySQL database.
Tried lot of solutions sill getting this error.
mapping file
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">anandhu</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Configuration file
<?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="Employee" table="emp">
<id name="empID" column="empID" type="int">
<generator class="assigned"></generator>
</id>
<property name="firstName" column="first_name" type="string">
<property name="lastName" column="second_name" type="string">
</class>
</hibernate-mapping>
This is my persistence class
public class Employee {
private int empID;
private String firstName;
private String lastName;
public int getID(){
return empID;
}
public void setID(int empID){
this.empID = empID;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
}
This is my test class
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class EmployeeTest {
public static void main(String[] args) {
Configuration cf = new Configuration();
cf.configure("employee.cfg.xml");
SessionFactory factory = cf.buildSessionFactory();
Session session = factory.openSession();
Employee employee = new Employee();
employee.setID(30);
employee.setFirstName("raju");
employee.setLastName("ryan");
Transaction transaction = session.beginTransaction();
session.save(employee);
System.out.println("updated");
transaction.commit();
session.close();
factory.close();
}
}
stack trace
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: employee.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at com.anandhu.hibernateproject.EmployeeTest.main(EmployeeTest.java:16)
Caused by: org.dom4j.DocumentException: Error on line 3 of document :
The processing instruction target matching "[xX][mM][lL]" is not allowed.
Nested exception:
The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
The problem with this lines
<property name="firstName" column="first_name" type="string">
<property name="lastName" column="second_name" type="string">
Should be
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="second_name" type="string" />
It would be more simply to find a solution if you show all stacktrace.
You can find examples of working with a configuration and a session here.
Upated
I check this mapping and it works fine. Looks like you have incorrect symbols (may be spaces) in the xml header. May be this will be helpfull Error: The processing instruction target matching “[xX][mM][lL]” is not allowed.
I have a class ActivityLink which extends from Activity. ActivityLink has a property as private Activity link; i don't want touch table Activity but i want create second table as ActivityLink . I use Java 1.7 and latest version of hibernate.
How can i realize it in hibernate by xml mapping?
public class ActivityLink extends Activity implements Serializable {
private static final long serialVersionUID = 1L;
private Activity link;
public ActivityLink( Activity link ){ this.link = link; }
// getter en setter
}
public class Activity implements Serializable {
private static final long serialVersionUID = 1L;
private String identity;
public Character precision;
public Date requestedTime;
public Date effectiveTime;
public String performerId;
public Date schedulerTime;
public Double fractionQty;
public Short UserId;
public Double totalVolume;
public Double restVolume;
public Activity() { }
// getter en setter
}
Activity.hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field">
<class name="de.j2ee.order.ActivityLink"
table="order_db..ActivityLink">
<composite-id class="de.j2ee.order.PK" name="pk">
<key-property name="identity" column="Identity_" access="field"/>
</composite-id>
<version name="version" column="Version_" access="field" type="java.lang.Long"/>
<property name="identity" column="Identity_" update="false" insert="false"/>
<property name="precision" column="Precision_"/>
<property name="requestedTime" column="RequestedTime_"/>
<property name="effectiveTime" column="EffectiveTime_"/>
<property name="performerId" column="PerformerId_"/>
<property name="schedulerTime" column="SchedulerTime_"/>
<property name="fractionQty" column="FractionQty_"/>
<property name="userId" column="UserId_"/>
<property name="totalVolume" column="TotalVolume_"/>
<property name="restVolume" column="RestVolume_"/>
<union-subclass name="de.j2ee.order.ActivityLink" table="order_db..Activity">
<property name="link" />
</union-subclass>-->
</class>
</hibernate-mapping>
If you want to use a single table for Activity and ActivityLink then you have to use Table Per Class hierarchy strategy. Follow below link for details:
10.1.1. Table per class hierarchy
So your mapping should look something like this:
<class name="Activity" table="Activity">
<id name="identity" column="Identity">
</id>
<discriminator column="ACTIVITY_TYPE" type="string"/>
<subclass name="ActivityLink" discriminator-value="Activity_Link">
...
</subclass>
</class>
Update:
If you want to create a table for the sub-class ActivityLink then you need to use the below strategy:
10.1.2. Table per subclass
For example:
<class name="Activity" table="Activity">
<id name="identity" column="Identity">
</id>
<joined-subclass name="ActivityLink" table="Activity_Link">
<key column="Activity_ID"/>
...
</joined-subclass>
</class>