hibernate change the column name in a select - java

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

Related

Problem with hibernate mapping (change anotations with xml)

I have a spring-hibernate application which work fine with JPA anotations, but I want to change anotations with xml configuration, but but I get this error:
org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [FROM User]
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [FROM User]
User.java
package com.fp.models;
public class User implements UserDetails {
private long id;
private String username;
private String password;
private Set<Role> authorities;
public User() {
}
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.fp.models.User" table="users">
<id name="id" type="long" column="user_id">
<generator class="native"/>
</id>
<property name="username" column="username" type="string"/>
<property name="password" column="password" type="string"/>
<set name="authorities" table="users_roles"
inverse="false" lazy="true" fetch="select" cascade="all" >
<key>
<column name="user_id" not-null="true" />
</key>
<many-to-many entity-name="com.fp.models.Role">
<column name="role_id" not-null="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
HibernateConfiguration.java -> https://pastebin.com/DrcGSBAp
this is the configuration which i use with the anotations
Method for test:
#Override
public int listAllUsers() {
try (Session session = sessionFactory.openSession()) {
String hql = "FROM User";
Query query = session.createQuery(hql);
if (query.list().size() == 0) {
return 0;
} else {
return 1;
}
} catch (HibernateException he) {
System.out.println(he.getMessage());
throw he;
}
}

Hibernate - Mapping association on un-related objects in xml

I have 2 classes:
User
RentedCar
public class User implements Serializable{
private String userName;
private Integer userId;
private String userParent;
}
public class RentedCar implements Serializable{
private Date stopDate;
private Date startDate;
private String carName;
private Integer carId;
private Integer userId; // Some userId from User.
}
These classes have their respective hbm.xml files. The underlying tables are un-related. Which means that I know that the userId in RentedCar is associated with the userId in User but there is no PK/FK relationship between them. I need to add a many-to-one association between RentedCar and User and one-to-many association between User and RentedCar. How should I do this in the hbm.xml files ?
These are the xml mappings:
<?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="User" table="user">
<composite-id>
<key-property name="userName" column="user_name" type="string"/>
<key-property name="userParent" column="user_parent" type="string"/>
</composite-id>
<property name="userId" column="user_id" type="int"></property>
</class>
</hibernate-mapping>
<?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="RentedCar" table="rented_car">
<composite-id>
<key-property name="stopDate" column="stop_date" type="date" />
<key-property name="carId" column="car_id" type="int" />
<key-property name="userId" column="user_id" type="int" />
</composite-id>
<property name="startDate" column="start_date" type="date"></property>
<property name="carName" column="car_name" type="float"></property>
</class>
</hibernate-mapping>
I think you should have something in your classes show that there is one-to-many relationship in order to do this in hbm.xml files :
public class User implements Serializable{
private String userName;
private Integer userId;
private String userParent;
private Set<RentedCar> rentedCars;
}
public class RentedCar implements Serializable{
private Date stopDate;
private Date startDate;
private String carName;
private Integer carId;
private User user;
}
Then in RentedCar.hbm.xml you can inside use :
<many-to-one name="user" class="User">
<column name="userId" not-null="true"></column>
</many-to-one>
And in User.hbm.xml :
<set name="rentedCars" table="rented_car" fetch="select">
<key>
<column name="userId" not-null="true"></column>
</key>
<one-to-many class=" RentedCar "/>
</set>
This tutorial may help you http://www.tutorialspoint.com/hibernate/hibernate_one_to_many_mapping.htm

Hibernate - insert data with one to many relationship

I am trying to insert data into a Patient table, which has a many-to-one relationship with Site. Site has a one-to-many relationship with Patient.
However, I get a org.postgresql.util.PSQLException: ERROR: insert or update on table "patients" violates foreign key constraint "fk_427e3ubwhw8n7a4id3mmrmjgj"
Detail: Key (patient_id)=(31) is not present in table "sites".
I have tried to create a set of patients, add my patient to this set, create a site object, then use this object to set the patients. I am not sure which part of this is going wrong.
Session session = this.getFactory().openSession();
Transaction transaction = null;
try{
transaction = session.beginTransaction();
Date parsedDob = Date.valueOf(dob);
Date parsedDateReg = Date.valueOf(dateReg);
Site site = new Site();
site.setSiteId(1);
IPatient p = new Patient();
p.setFirstName(firstName);
p.setLastName(lastName);
p.setDob(parsedDob);
p.setDateRegistered(parsedDateReg);
p.setSite(site);
Set<IPatient> patientSet = new HashSet<IPatient>();
patientSet.add(p);
site.setPatients(patientSet);
session.save(site);
session.save(p);
transaction.commit();
}catch(Exception e){
e.printStackTrace();
}
My Patient.hbm.xml file is:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
<class name="Patient" table="patients">
<id name="patientId" column="patient_id">
<generator class="sequence" />
</id>
<version name="version" column="version" />
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<property name="dob" column="dob" />
<property name="gender" column="gender" />
<property name="dateRegistered" column="date_registered" />
<many-to-one name="site" class="com.example.model.Site" not-null="true" />
<set name="visits" cascade="all">
<key column="visit_id" />
<one-to-many class="Visit" />
</set>
</class>
My Site.hmx.xml is:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
<class name="Site" table="sites">
<id name="siteId" column="site_id">
<generator class="sequence" />
</id>
<version name="version" column="version" />
<property name="name" column="name" />
<set name="patients" cascade="all">
<key column="patient_id" />
<one-to-many class="Patient" />
</set>
</class>
My Patient.java
public class Patient implements IPatient{
private Integer version;
private Integer patientId;
private Set<IVisit> visits;
private Site site;
private String firstName;
private String lastName;
private Date dob;
private Gender gender;
private Date dateRegistered;
public Patient(){
}
}
My Site.java
public class Site {
private Integer siteId;
private Integer version;
private Set<IPatient> patients;
private String name;
public Site(){
}
}
After the line below you should save your site object to db;
site.setSiteId(1);
session.save(site);
After that you can set site object to patient;
p.setSite(site);

I can't insert foreign key

I have a node db with five pieces of data:
id(int, PK)
question(varchar)
result(varchar)
left_id(int, FK)
right_id(int, FK)
and two foreign keys in the same table
left_id -> id
right_id -> id
here is my bean
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name="id")
#NotNull
private int id;
#Column (name = "question")
private String question;
#Column ( name = "result")
private String result;
#OneToOne(fetch= FetchType.LAZY)
#JoinColumn(name="left_id", referencedColumnName="id", insertable=true, updatable=true)
private Nodes left;
#OneToOne(fetch= FetchType.LAZY)
#JoinColumn(name="right_id", referencedColumnName="id", table="node", insertable=true, updatable=true)
private Nodes right;
and here is my dao
public void insert_question(String question, int left) throws HibernateException
{
try
{
Session session = getSession();
Transaction tx = session.beginTransaction();
Nodes node = new Nodes();
Nodes leftNode = new Nodes();
//insert question
node.setQuestion(question);
// insert left_id with fk
leftNode.setId_node(left);
node.setLeftNodes(leftNode);
session.saveOrUpdate(node);
tx.commit();
session.close();
}
catch (HibernateException e)
{
e.printStackTrace();
}
}
I have a same insert method for result but without foreign key.
My new question and new result are insert my db but not my left_id.
In Eclipse, hibernate tell me
Infos: Hibernate: select nodes_.id, nodes_.question as question0_, nodes_.result as result0_ from node nodes_ where nodes_.id=?
Infos: Hibernate: insert into node (question, result, id) values (?, ?, ?)
Infos: Hibernate: insert into node (question, result, id) values (?, ?, ?)
When hibernate insert a new data, why there are no left/right_id ?
thanks
EDIT:
I changed my hbm. Before it was like that
<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>
<one-to-one name="left" class="com.beans.Nodes" access="field"></one-to-one>
<one-to-one name="right" class="com.beans.Nodes" access="field"></one-to-one>
</class>
</hibernate-mapping>
and now it's like that
<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" not-null="false"/>
</property>
<property name="result" type="java.lang.String">
<column name="result" not-null="false"/>
</property>
<many-to-one name="Left"
column="left_id"
unique="true"
not-null="false"
/>
<many-to-one name="Right"
column="right_id"
unique="true"
not-null="false"
/>
</class>
</hibernate-mapping>
and it's works !

one to one relationship with hibernate

I try to create a one to one relationship between two tables.
One of them is Person:
public class Person implements Serializable {
static final long serialVersionUID = 1L;
private long id;
private String _email;
private String _pass;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return _email;
}
public void set_email(String _email) {
this._email = _email;
}
public String getPass() {
return _pass;
}
public void set_pass(String _pass) {
this._pass = _pass;
}
}
and the second is ReqC2dmRegId table:
public class ReqC2dmRegId implements Serializable {
private static final long serialVersionUID = 1L;
Person person;
String C2dmid;
private long id;
public ReqC2dmRegId(){}
public String getC2dmid() {
return C2dmid;
}
public void setC2dmid(String c2dmid) {
C2dmid = c2dmid;
}
public ReqC2dmRegId(Person person, String C2dmid) {
super();
this.person = person;
this.C2dmid = C2dmid;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Now, in my program, I always create the Person first and only when I need I add this ReqC2dmRegId.
Now, what I try to do is to link this two tables. I mean, when I persist this ReqC2dmRegId (of course I add to the person in ReqC2dmRegId the right id) I want my ReqC2dmRegId to update or save a new row with the right Person id.
These are my hbm files:
ReqC2dmRegId.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 Mar 26, 2012 11:29:57 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="c2dm.ReqC2dmRegId" table="REQC2DMREGID">
<id name="id" type="long">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<one-to-one name="person" class="Entities.Person" cascade="all" />
<property name="C2dmid" type="java.lang.String">
<column name="C2DMID" />
</property>
</class>
</hibernate-mapping>
Person.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 Mar 26, 2012 11:29:57 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="Entities.Person" table="PERSON">
<id name="id" type="long">
<column name="ID" />
<generator class="increment" />
</id>
<property name="_email" type="java.lang.String" access="field">
<column name="_EMAIL" />
</property>
<property name="_pass" type="java.lang.String" access="field">
<column name="_PASS" />
</property>
</class>
</hibernate-mapping>
What am I doing wrong?
When I try to run:
//this should to update or save the object in DB
public void update (Object query){
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
//em.createNativeQuery(query).executeUpdate();
em.merge(query);
em.flush();
em.getTransaction().commit();
em.close();
}
I get :
attempted to assign id from null one-to-one property:Person
In the end, it should look like this:
Person
**id email _pass**
2 lala#gmail.com 1234
ReqC2dmRegId
**id REQC2DMREGID**
2 ffgghhjj
Update:
after i gave up try to understand way it's not working
i change my ReqC2dmRegId.hbm.xml
to look like this (many-to-one):
<?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 Mar 27, 2012 9:58:08 PM by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping>
<class name="c2dm.ReqC2dmRegId" table="REQC2DMREGID">
<id name="id" type="long">
<column name="ID" />
<generator class="identity" />
</id>
<many-to-one name="person" class="Entities.Person" fetch="join" unique="true" cascade="save-update" not-null="true" >
<column name="PERSON" />
</many-to-one>
<property name="C2dmid" type="java.lang.String">
<column name="C2DMID" />
</property>
</class> </hibernate-mapping>
and this is working fine the problem is when i try to modify ReqC2dmRegId table
with my update method it create a now row with the same personid
id person_id C2dmid
1 3 asd123
2 3 dfvghj
way it's not update the right row instated create a new one and although i make the "many to one" property to be unique="true"?
thanks in advance
You have to be clear about the kind of relation: Is one-to-one or many-to-one?
Look like is a many-to-one unidirectional relation.
Here is an example with Annotations:
#Entity
#Table(name="PERSON")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String _email;
private String _pass;
//getters and setters
}
And the other class:
#Entity
#Table(name="ReqC2dmRegId")
public class ReqC2dmRegId {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToOne
#JoinColumn(name = "PERSON_ID")
private Person person;
//getters and setters
}

Categories

Resources