I am getting ClassCastException: at.sheldor5.tr.api.time.RecordType cannot be cast to java.lang.Boolean because Hibernate 5.2.9.FINAL completly ignores my converter:
<?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 package="at.sheldor5.tr.api.time">
<class name="Record" table="RECORDS">
<id name="id" type="int" column="PK_RECORD_ID">
<generator class="native"/>
</id>
<many-to-one name="user" column="FK_USER_MAPPING_ID" class="at.sheldor5.tr.api.user.UserMapping"/>
<property name="date" type="java.time.LocalDate" column="DATE" index="I_DATE"/>
<property name="time" type="java.time.LocalTime" column="TIME"/>
<property name="type" type="boolean" column="TYPE">
<type name="at.sheldor5.tr.persistence.converter.RecordTypeAttributeConverter"/>
</property>
</class>
</hibernate-mapping>
Converter:
#Converter
public class RecordTypeAttributeConverter implements AttributeConverter<RecordType, Boolean> {
#Override
public Boolean convertToDatabaseColumn(final RecordType attribute) {
if (attribute == null) {
return null;
}
return attribute.getBoolean();
}
#Override
public RecordType convertToEntityAttribute(final Boolean dbData) {
return RecordType.getType(dbData);
}
}
The only thing I can see is that hibernate ignores my converter because of some random things.
Any suggestions (except clean/rebuild which I already tried or hard reset)?
EDIT: my converter won't even gets loaded ...
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.
EDIT :
The problem solved,I didnt write the exactly loaction of the entites in the XML files,Where the one-many-tag.
Im trying to map these classes to database and i get this error :
Exception in thread "main" org.hibernate.MappingException: Association references unmapped class: Reservation
at org.hibernate.cfg.HbmBinder.bindCollectionSecondPass(HbmBinder.java:2557)
at org.hibernate.cfg.HbmBinder$CollectionSecondPass.secondPass(HbmBinder.java:2808)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:70)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1695)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at entities.chairandtabletest.main(chairandtabletest.java:39)
I tried to find where is my problem,I read about this exception and i dont understand where is the problem in my program.
The classes :
public class Customer {
private Integer id;
private String fullName;
private String address;
private String email;
private String phoneNumber;
private List<Reservation> reservations = new ArrayList<Reservation>();
}
public class Reservation{
private Integer id;
private String date;
private Integer totalSum;
private boolean isDeliever;
private List<Item> items = new ArrayList<Item>();
}
public class Item {
private Integer id;
private String name;
private Integer price;
}
The tables :
CREATE TABLE ITEM(
item_id INT NOT NULL AUTO_INCREMENT,
item_name VARCHAR(40),
item_price INT NOT NULL,
reservation_id INT,
PRIMARY KEY(item_id)
);
CREATE TABLE RESERVATION(
reservation_id INT NOT NULL AUTO_INCREMENT,
reservarion_date VARCHAR(255),
reservtion_delivery BOOL,
reservation_total_sum INT,
customer_id INT,
PRIMARY KEY(reservation_id)
);
CREATE TABLE CUSTOMERS(
customer_id INT NOT NULL AUTO_INCREMENT,
customer_full_name VARCHAR(40),
customer_address VARCHAR(255),
customer_email VARCHAR(255),
customer_phone_number VARCHAR(20),
PRIMARY KEY(customer_id)
);
The XML files :
<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/chairandtable?serverTimezone=UTC</property>
<property name="hibernate.connection.username">aliali</property>
<property name="hibernate.connection.password">password</property>
<mapping resource="props/customer.hbm.xml"/>
<mapping resource="props/reservation.hbm.xml"/>
<mapping resource="props/item.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<?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="entities.Customer" table="customers">
<meta attribute="class-description">
This class contain customers details.
</meta>
<id name="id" type="integer" column="customer_id">
<generator class="identity"/>
</id>
<bag name="reservations" cascade="all">
<key column= "customer_id"/>
<one-to-many class="Reservation"/>
</bag>
<property name="fullName" column="customer_full_name" type="string"/>
<property name="address" column="customer_adress" type="string"/>
<property name="email" column="customer_email" type="string"/>
<property name="phoneNumber" column="customer_phone_number" type="string"/>
</class>
</hibernate-mapping>
<?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 ="entities.Reservation" table="reservation">
<meta attribute="class-description">
This class contain reservation detail.
</meta>
<id name ="id" column="reservation_id" type="integer">
<generator class="identity"/>
</id>
<bag name="items" cascade="all">
<key column="reservation_id"/>
<one-to-many class="Item"/>
</bag>
<property name="date" column="reservation_date" type="string"/>
<property name="totalSum" column="reservation_total_sum" type="integer"/>
<property name="isDeliver" column="reservtion_delivery" type="boolean"/>
</class>
</hibernate-mapping>
<?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="entities.Item" table="item">
<id name= "id" column="item_id" type="integer">
<generator class="identity"/>
</id>
<property name="name" column="item_name" type="string"/>
<property name="price" column="item_price" type="integer"/>
</class>
</hibernate-mapping>
I think the problem is the tables i declared , Maybe the are not matching the
xml file.
You need to change the order of *hbm.xml configs to:
<mapping resource="props/item.hbm.xml"/>
<mapping resource="props/reservation.hbm.xml"/>
<mapping resource="props/customer.hbm.xml"/>
And add the "entities" package to all of your one-to-many mappings like this:
<one-to-many class="entities.Item"/>
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>
I have created an application for converting the Hibernate criteria list results into json, first whe i tried i got Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter
I resolved that when i googled i came across this stuff Could not serialize object cause of HibernateProxy
Now i am getting the StackOverflowError as shown below
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
this_.id as id1_1_0_,
this_.base_id as base_id2_1_0_,
this_.name as name3_1_0_
from
testdatabase12.child this_
Hibernate:
select
base0_.id as id1_0_0_,
base0_.name as name2_0_0_
from
testdatabase12.base base0_
where
base0_.id=?
Hibernate:
select
childs0_.base_id as base_id2_0_0_,
childs0_.id as id1_1_0_,
childs0_.id as id1_1_1_,
childs0_.base_id as base_id2_1_1_,
childs0_.name as name3_1_1_
from
testdatabase12.child childs0_
where
childs0_.base_id=?
Exception in thread "main" java.lang.StackOverflowError
at java.util.LinkedHashMap$LinkedHashIterator.<init>(LinkedHashMap.java:345)
at java.util.LinkedHashMap$LinkedHashIterator.<init>(LinkedHashMap.java:345)
at java.util.LinkedHashMap$ValueIterator.<init>(LinkedHashMap.java:387)
at java.util.LinkedHashMap$ValueIterator.<init>(LinkedHashMap.java:387)
at java.util.LinkedHashMap.newValueIterator(LinkedHashMap.java:397)
at java.util.HashMap$Values.iterator(HashMap.java:910)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:203)
at com.dao.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:52)
at com.dao.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:1)
:
:
My code is as given below
App.java
public class App {
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List names = session.createCriteria(Child.class).list();
GsonBuilder b = new GsonBuilder();
b.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);
Gson gson = b.create();
String jsonNames = gson.toJson(names);
System.out.println("jsonNames = " + jsonNames);
session.close();
}
}
Base.java
public class Base implements java.io.Serializable {
private Integer id;
private String name;
private Set childs = new HashSet(0);
// getters and setters
}
Base.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 2, 2014 5:23:25 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.mappings.Base" table="base" catalog="testdatabase12">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="20" />
</property>
<set name="childs" table="child" inverse="true" lazy="true" fetch="select">
<key>
<column name="base_id" />
</key>
<one-to-many class="com.mappings.Child" />
</set>
</class>
</hibernate-mapping>
Child.java
public class Child implements java.io.Serializable {
private Integer id;
private Base base;
private String name;
//getters and setters
}
Child.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 2, 2014 5:23:25 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.mappings.Child" table="child" catalog="testdatabase12">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<many-to-one name="base" class="com.mappings.Base" fetch="select">
<column name="base_id" />
</many-to-one>
<property name="name" type="string">
<column name="name" length="20" />
</property>
</class>
</hibernate-mapping>
I think it's about List. You can use ArrayList for make JSON from List.
Try this code i am not sure but when you clear red marks it will work.
public class App {
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List names = session.createCriteria(Child.class).list();
GsonBuilder b = new GsonBuilder();
b.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);
Gson gson = new Gson();
//seperate adding
gson.toJson("propertyName" , List.get(0).getter...());
gson.toJson("propertyName" , List.get(1).getter...());
session.close();
}
}
I am following this titorial on roseindia to get basics of Hibernate : "http://roseindia.net/hibernate/hibernate-update.shtml"
My code is as below and getting the error for the same. Please assist me to fix it!
Java Code:
public class UpdateExample {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session sess = null;
try {
SessionFactory fact = new Configuration().configure().buildSessionFactory();
sess = fact.openSession();
Transaction tr = sess.beginTransaction();
Insurance ins = (Insurance)sess.get(Insurance.class, new Long(1));
ins.setInsuranceName("Jivan Dhara");
ins.setInvestementAmount(20000);
ins.setInvestementDate(new Date());
sess.update(ins);
tr.commit();
sess.close();
System.out.println("Update successfully!");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
And
public class Insurance {
private String insuranceName;
private double investementAmount;
private Date investementDate;
public String getInsuranceName() {
return insuranceName;
}
public void setInsuranceName(String insuranceName) {
this.insuranceName = insuranceName;
}
public double getInvestementAmount() {
return investementAmount;
}
public void setInvestementAmount(double investementAmount) {
this.investementAmount = investementAmount;
}
public Date getInvestementDate() {
return investementDate;
}
public void setInvestementDate(Date investementDate) {
this.investementDate = investementDate;
}
}
And my contact.hbm.xml :
<?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="Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
<class name="Book" table="book">
<id name="lngBookId" type="long" column="id" >
<generator class="increment"/>
</id>
<property name="strBookName">
<column name="bookname" />
</property>
</class>
<class name="Insurance" table="insurance">
<id name="insuranceName" type="String" column="InsuranceName" >
/>
</id>
<property name="investmentAmount">
<column name="InvestmentAmount" />
</property>
<property name="investmentDate">
<column name="InvestmentDate" />
</property>
</class>
</hibernate-mapping>
And the error i am getting is:
"Error reading resource: contact.hbm.xml"
Also I have created db table by name Insurance with those column fields.
Thanks
Sneha
Isn't something missing in the hbm.xml file? It isn't a complete XML file.
You need to place the hbm.xml file together with the compiled class file for your class.
Is this your whole .hbm.xml file? If so, it's incomplete - it lacks proper structure shown here: http://roseindia.net/hibernate/hibernateormapping.shtml
<?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="roseindia.tutorial.hibernate.Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
you have to define two POJO classes
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Book" table="book" >
<id name="lngBookId" column="id" type="long">
<generator class="increment"></generator>
</id>
<property name="strBookName" type="string">
<column name="bookname" sql-type="VARCHAR2(55)"/>
</property>
</class>
<class name="Insurance" table="insurance" >
<property name="firstName" type="string">
<column name="FIRSTNAME" sql-type="VARCHAR2(55)"/>
</property>
<property name="lastName" type="string">
<column name="LASTNAME" sql-type="VARCHAR2(55)"/>
</property>
<property name="email" type="string">
<column name="EMAIL" sql-type="VARCHAR2(55)"/>
</property>
</class>
</hibernate-mapping>