Adding lazy=false using annotation in hibernate java - java

I am having below xml mapping file where they have used many-to-one column,
<hibernate-mapping>
<class name="com.example.offerUser"
table="offerUser">
<id name="offerUserId" type="java.lang.Long">
<column name="OOFER_USER_ID"/>
<generator class="identity"/>
</id>
<many-to-one name="offer"
class="com.example.offer"
fetch="select" lazy="false">
<column name="OFFER_ID"/>
</many-to-one>
<many-to-one name="user"
class="com.example.User"
fetch="select" lazy="false">
<column name="USER_ID"/>
</many-to-one>
</class>
</hibernate-mapping>
and here is annotation code,where i am replacing xml by annotation,but how to replace lazy="false" in annotation.
#Entity
#Table(name = "offerUser")
#JsonIgnoreProperties(ignoreUnknown = true)
public class offerUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "OOFER_USER_ID")
private Long offerUserId;
#ManyToOne(fetch = FetchType.LAZY)
#Fetch(FetchMode.SELECT)
#JoinColumn(name="OFFER_ID")
private offer offer;
#ManyToOne(fetch = FetchType.LAZY)
#Fetch(FetchMode.SELECT)
#JoinColumn(name="USER_ID")
private User user;
}
I searched in google,but i they have not mentioned any thing about setting lazy=false, instead they have used 'Optional = false'.Why is it so.?Please help me on this.

In hibernate annotations ( #ManyToOne ) default fetch type is EAGER.

Related

Don't change the reference to a collection with cascade="all-delete-orphan" while changing properyt in an entity

I am getting above exception when i tried to change the value of an property in the entity but not the collection.
I retrieved value by tinyUrl even though it is not an primary key in the table.
Below is part of the code snippet
Sample sample = retrieveContentByUrl("https://text.com");
sample.setDescription("Sample");
getSession().saveorupdate(sample);
Sample.java
class Sample {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private int id;
#Column(name="TINY_URL")
private int tinyUrl;
#Column(name="DESCRIPTION")
private String description;
#OneToMany(mappedBy="sample",fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
private Set<TextBooks> textBooks = new HashSet<TextBooks>();
//Having getters and setters for all above variables
}
TextBooks.java
class TextBooks {
#ManyToOne
#JoinColumn(name = "ID")
private Sample sample;
//Having getters and setters for all above variables
}
.hbm file
<class name="com.sample.Sample"
table="SAMPLE" >
<id name="id" column="ID" type="long">
<generator class="identity" />
</id>
<property column="TINY_URL" name="tinyUrl" />
<property column="DESCRIPTION" name="description" />
<set name="textBooks" inverse="true" cascade="all-delete-orphan">
<key column="ID" />
<one-to-many
class="com.text.TextBooks" />
</set>
</set>
</class>

hibernate change the column name in a select

I have a table (node) with 3 data
- id(pk)
- question
- result
and 2 foreign key (many-to-one)
- LEFT_ID
- RIGHT_ID
here my hbm
<?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.beans.Nodes" table="node">
<id name="id" type="int" access="field">
<column name="id" />
<generator class="assigned" />
</id>
<property name="question" type="java.lang.String">
<column name="question" />
</property>
<property name="result" type="java.lang.String">
<column name="result" />
</property>
<many-to-one column="LEFT_ID" name="left" class="com.beans.Nodes" insert="false" update="false"></many-to-one>
<many-to-one column="RIGHT_ID" name="right" class="com.beans.Nodes" insert="false" update="false"></many-to-one>
</class>
</hibernate-mapping>
and my bean with getter/setter on LEFT/RIGHT_ID
#Entity
#Table (name = "node")
public class Nodes
{
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column (name = "question")
private String question;
#Column ( name = "result")
private String result;
private Nodes LEFT_ID;
private Nodes RIGHT_ID;
public Nodes getLeftNodes()
{
return LEFT_ID;
}
public void setLeftNodes(Nodes LEFT_ID)
{
this.LEFT_ID=LEFT_ID;
}
public Nodes getRightNodes()
{
return RIGHT_ID;
}
public void setRifhtNodes(Nodes right)
{
this.RIGHT_ID=right;
}
}
But when i deploy my project, i have this error
**Query: ReadAllQuery(referenceClass=Nodes sql="SELECT id, question, result, LEFT_ID_id, RIGHT_ID_id FROM node")**
When hibernate is a select, he change the name of the column. LEFT_ID becomes LEFT_ID_id and inevitably he finds nothing !
Why hibernate change the name of the LEFT_ID column ?
thanks

Mapping Hibernate

I have 2 Entities: Technologie and Competence
Each competence can have 1 or more Techno
so i have generate the classes by Hibernate
and he gave me 3 classes Model
Technologie
Competence
TechnologieId
and now i'm confused about how to add a technologie
and what is the point of TechnoligieId ?
Technologie.java
public class Technologie implements java.io.Serializable {
private TechnologieId id;
private Competence competence;
private String libelleTechnologie;
}
TechnologieId.java
public class TechnologieId implements java.io.Serializable {
private int idCompetence;
private int idTechnologie;
}
Technologie.hbm.xml
<class name="com.model.Technologie" table="technologie" catalog="gestioncollaborateur">
<composite-id name="id" class="com.model.TechnologieId">
<key-property name="idCompetence" type="int">
<column name="idCompetence" />
</key-property>
<key-property name="idTechnologie" type="int">
<column name="idTechnologie" />
</key-property>
</composite-id>
<many-to-one name="competence" class="com.model.Competence" update="false" insert="false" fetch="select">
<column name="idCompetence" not-null="true" />
</many-to-one>
<property name="libelleTechnologie" type="string">
<column name="libelleTechnologie" length="254" />
</property>
</class>
If the relationship is mentioned correctly in the question. Then why dont you do something like this?
public class Technologie implements java.io.Serializable {
private id;
private Competence competence;
private String libelleTechnologie;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="<yourForeign Key for Competence>")
public Competence getCompetence() {
return competence;
}
}
And the Competence Class such as.
public class Competence implements java.io.Serializable {
private id;
private List<Technologie> technologies;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(mappedBy = "<name of the property of Competence in Technology class>")
public List<Technologies> getTechnologies() {
return technologies;
}
}
Also, this is if the Technology is the managing side of the relationship. Basically, what it means is you will do a save / update on the Technologie primarily which will handle the relationship.
If you do want the #OneToMany side as the managing side. you would have to add the insertable=false, updatable=false attributes in the #JoinColumn annotation for the the getTechnologies method.

can we map non-object propety to an object in Many-to-one relationship of hibernate?

I have a very specific scenario as follow.
public class Person
{
Long id;
Collection<PersonRelation> personRelationCollection = new LinkedHashSet<PersonRelation>();
/**
has respective getter and setter
**/
}
public class PersonRelation
{
Long id;
Long parentPersonId; // here I don't want parentPersonId of type Person
Long childPersonId; // here also I don't want childPersonId of type Person
String relationType;
/**
has respective getter setter
**/
}
In my mapping files I have following
<class name="Person" table="PERSON">
<id name="id" column="IDENTIFIER">
<generator class="native"/>
</id>
<set
name="personRelationCollection"
table="PERSON_RELATION"
cascade="all"
>
<key column="PARENT_PERSON_ID"/>
<one-to-many class="PersonRelation"/>
</set>
</class>
and
<class name="PersonRelation" table="PERSON_RELATION">
<id name="id" column="IDENTIFIER">
<generator class="native"/>
</id>
<!-- following many-to-one mapping doesn't work-->
<!-- I need help here to satisfy my requirement -->
<many-to-one
name="parentPersonId"
column="PARENT_PERSON_ID"
class="Person"
not-null="true"/>
<Property name="childPersonId" column="CHILD_PERSON_ID"/>
<property name="relationType" column="RELATION_TYPE"/>
</class>
In this example, as in PersonRelation class, attribute parentPersonId is Long and not type of Person, I'm getting
org.hibernate.MappingException: Association references unmapped class PersonRelation
$
Please help.
Forget about references by id. In Hibernate you work with objects, not tables.
I guess your code could be written like this:
#Entity
#Table(name="your_table")
public class Item{
private Long id;
private Item parentItem;
private List<Item> children;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId(){
}
#ManyToOne()//Your options
public Item getParentItem(){
}
#OneToMane(mappedBy="parentItem")
public List<Item> getChildren(){
}
//Setters omitted
}
finally i found answer my own. Very small thing we have to do as follow.
<class name="PersonRelation" table="PERSON_RELATION">
<id name="id" column="IDENTIFIER">
<generator class="native"/>
</id>
<!-- here remove many-to-one mapping ---- it's not needed-->
<!-- treet participantPersonId as a simple property and everything will work -->
<Property name="parentPersonId" column="PARENT_PERSON_ID" type="Long"/>
<Property name="childPersonId" column="CHILD_PERSON_ID"/>
<property name="relationType" column="RELATION_TYPE"/>
</class>
This works perfectly fine. :)
Here, when you insert Person object, then it will not inset PersonRelation object too. You have to explicitly insert PersonRelation object. Perhaps, when we retrieve Person object, then it will gives you collection of PersonRelation. Here no need to retrieve PersonRelation collection explicitly.

Provided id of the wrong type hibernate

I am getting error:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class BEntity. Expected: class BEntity, got class AEntity
public class BEntity implements Serializable{
#Id
#Column(name = "NUM")
private String num;
#Id
#Column(name = "INIT")
private String init;
#Column(name = "V_CNT")
private Integer vcnt;
//{{{some column omitted}}}//
}
public class AEntity implements Serializable{
#Id
#Column(name = "NUM")
private String num;
#Id
#Column(name = "INIT")
private String init;
#OneToOne
#PrimaryKeyJoinColumns({
#PrimaryKeyJoinColumn(name="NUM", referencedColumnName="NUM"),
#PrimaryKeyJoinColumn(name="INIT", referencedColumnName="INIT")
})
private BEntity bEntity;
}
HQL query:
String queryString = "FROM AEntity AS A " +
"LEFT JOIN A.bEntityAS B " +
"WHERE A.INIT||A.NUM IN (:carList) AND A.INIT IN (:initList) AND A.NUM IN (:numberList) " +
"AND B.TRUK_AXL_CNT > 0";
Hibernate gen-code
select aentity0_.NUMBER as NUMBER4_0_, aentity0_.INITIAL as INITIAL4_0_, bentity_p1_.NUMBER as NUMBER5_1_, bentity_p1_.INITIAL as INITIAL5_1_, aentity0_.V_CNT as VCNT3_4_0_, aentity0_.EIN as EIN4_0_, aentity0_.TYP as TYP5_4_0_, aentity0_.TRUK_CNT as TRUK6_4_0_, bentity_p1_.TRUK_AXL_CNT as TRUK3_5_1_ from USR.aentity aentity0_ left outer join USR.bentity_PRIMARY bentity_p1_ on aentity0_.NUMBER=bentity_p1_.NUMBER and aentity0_.INITIAL=bentity_p1_.INITIAL
where (aentity0_.INITIAL||aentity0_.NUMBER in (?,?,?))
and (aentity0_.INITIAL in (?,?,?))
and (aentity0_.NUMBER in (?, ?, ?))
and bentity_p1_.TRUK_AXL_CNT>0
When I run the code in SQL Explorer it works only running it in code cause the issue...
Looks like this is a defect in hibernate version 3.2.6 which is still not resolved. Came across this JIRA.
Having multiple #Id is supported by Hibernate but seems it fails under one to one mapping, suggested way of resolving this is to use single CompositeKey, which means you create a PK class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class PKClass implements Serializable {
#Column(name = "NUM")
private String num;
#Column(name = "INIT")
private String init;
//gettter setter here
}
then in your Entity use this as the ID
public class BEntity implements Serializable{
#Id
private PKClass pkClass = null;
#Column(name = "V_CNT")
private Integer vcnt;
//{{{some column omitted}}}//
}
public class AEntity implements Serializable{
#Id
private PKClass pkClass = null;
#OneToOne
#PrimaryKeyJoinColumns({
#PrimaryKeyJoinColumn(name="NUM", referencedColumnName="NUM"),
#PrimaryKeyJoinColumn(name="INIT", referencedColumnName="INIT")
})
private BEntity bEntity;
}
I faced the same issue. I had two separate PK classes that had the same fields. So I removed one PK and used only one in the owner and child entity. This solved the problem.
I had the same problem.
Started situation
Primary key on master table
<composite-id name="id" class="model.E1Id">
<key-property name="taxpayerId" type="int">
<column name="TaxpayerID" />
</key-property>
<key-property name="year" type="int">
<column name="Year" />
</key-property>
</composite-id>
Primary key on detail table
<composite-id name="id" class="model.E1dataFromTaxPayerFolderId">
<key-property name="tid" type="int">
<column name="tID" />
</key-property>
<key-property name="year" type="int">
<column name="Year" />
</key-property>
</composite-id>
After repair
I change the class of detail table composite-id and i set the class of primary table like this:
<composite-id name="id" class="model.E1Id">
<key-property name="tid" type="int">
<column name="tID" />
</key-property>
<key-property name="year" type="int">
<column name="Year" />
</key-property>
</composite-id>
After that is necessary (if you have different names) to add in your primarykey class (in my case E1Id) the property tid (with getter and setter methods)

Categories

Resources