How to implement a self join in hibernate

Source : http://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/

We have a create table in the database.

CREATE TABLE employee (
employee_id NUMBER(10) NOT NULL,
firstname VARCHAR2(50) NULL DEFAULT NULL,
lastname VARCHAR(50) NULL DEFAULT NULL,
manager_id NUMBER(10) NULL DEFAULT NULL,
PRIMARY KEY (’employee_id’),
CONSTRAINT ‘FK_MANAGER’ FOREIGN KEY (‘manager_id’) REFERENCES ’employee’ (’employee_id’)
);

Here in Employee table, we defined a column MANAGER_ID which is mapped to the same table’s primary key. Thus for each employee we will store its manager’s id also. Manager will be yet another employee in this table

We will be using annotations to implement this in hibernate:

@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@Column(name="EMPLOYEE_ID")
@GeneratedValue
private Long employeeId;

@Column(name="FIRSTNAME")
private String firstname;

@Column(name="LASTNAME")
private String lastname;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="manager_id")
private Employee manager;

@OneToMany(mappedBy="manager")
private Set subordinates = new HashSet();

public Employee() {
}

public Employee(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}

// Getter and Setter methods
}

Note that in Employee entity class, we defined two new attributes: Employee manager and Set subordinates. Attribute manager is mapped with @ManyToOne annotation and subordinates is mapped with @OneToMany. Also within @OneToMany attribute we defined mappedBy=”manager” making manager as the relationship owner and thus which manages the foreign relationship within table.

Also the annotation @JoinColumn is defined on manager making it the relationship owner. @JoinColumn defines the joining column which in our case is manager_id.

How to integrate Spring and Hibernate

Here are the few tips I have gathered on how to integrate spring and hibernate.

Create your bean.xml something like this…

 












Connection.properties




${db.driverClassName}


${db.url}


${db.username}


${db.password}








com.usermanagement.pojo.User
com.usermanagement.pojo.Role
com.usermanagement.pojo.Privilege
com.usermanagement.pojo.Password
com.usermanagement.pojo.PasswordPolicy





org.hibernate.dialect.Oracle10gDialect
update
true

true
<!--org.hibernate.cache.SingletonEhCacheProvider-->
org.hibernate.cache.EhCacheProvider
































The list of jars that you might need are

  1. antlr-2.7.6.jar
  2. asm-1.5.3.jar
  3. axis2-spring-1.6.1.jar
  4. cglib-2.1_3.jar
  5. commons-collections-3.1.jar
  6. commons-dbcp-1.4.jar
  7. commons-logging-1.0.4.jar
  8. commons-pool-1.6.jar
  9. dom4j-1.6.1.jar
  10. hibernate-3.2.0.ga.jar
  11. hibernate-3.2.6.jar
  12. hibernate-annotations-3.4.0.GA.jar
  13. hibernate-commons-annotations-3.1.0.GA.jar
  14. hibernate-core-3.3.0.SP1.jar
  15. hibernate-entitymanager.jar
  16. hibernate-jpa-2.0-api-1.0.0.Final.jar
  17. jta-1.1.jar
  18. log4j-1.2.14.jar
  19. ojdbc14.jar
  20. org.springframework.asm-3.0.0.RELEASE.jar
  21. org.springframework.beans-3.0.0.RELEASE.jar
  22. org.springframework.context-3.0.0.RELEASE.jar
  23. org.springframework.core-3.0.0.RELEASE.jar
  24. org.springframework.expression-3.0.0.RELEASE.jar
  25. org.springframework.jdbc-3.0.0.RELEASE.jar
  26. org.springframework.orm-3.0.0.RELEASE.jar
  27. org.springframework.web.servlet-3.0.1.RELEASE-A.jar
  28. slf4j-api-1.6.1.jar
  29. spring-tx-3.0.0.RELEASE.jar

duplicate import try, using auto-import=”false”

How to use same entity class in two different packages in hibernate?

Source : http://isolasoftware.it/2011/10/14/hibernate-and-jpa-error-duplicate-import-try-using-auto-importfalse/

Using Hibernate and JPA you cannot have two classes with the same name (on different packages) mapped. This raise an error at runtime:
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyClass refers to both

To solve this issue on the Entity annotation of com.intre.MyClass and com.dummy.Class add the property name.

package com.intre;
@Entity(name = "com.intre.myclass")
@Table(name = "MyClass")
public class MyClass

package com.dummy;
@Entity(name = "com.dummy.myclass")
@Table(name = "MyClass")
public class MyClass

How to upload file using struts and hiberate?

How to upload file using struts and hibernate?

I spent 5-6 hours figuring out how can I upload a file into Blob in a database. So I decided to write a short article.

Add enctype=”multipart/form-data” in the form tag (in JSP)



Add 2 fields in ActionForm, one which is populated via struts framework.
Second one which is read by hibernate i.e. uploadedBlob

// This is filled by the code written in Action Class.
// This has to be done manually and is not done automatically.
private Blob uploadedBlob;
public Blob getUploadedBlob() {
return uploadedBlob;
}

public void setUploadedBlob(Blob uploadedba) {
this.uploadedBlob = uploadedba;
}

// This is the actual FormFile which gets populated into the ActionForm
// by struts framework.
private FormFile uploadedfile;
public FormFile getUploadedfile() {
return uploadedfile;
}

public void setUploadedfile(FormFile uploadedfile) {
this.uploadedfile = uploadedfile;
}

Add the following in formbean.hbm.xml


In Action Class, convert FormFile to Blob and set it in FormBean (while saving)

// Convert FormFile to a byte Array
byte[] byteArray=formbean.getUploadedfile().getFileData();
// Convert this byteArray to a blob
Blob myblob=Hibernate.createBlob(byteArray);
formbean.setUploadedBlob(myblob);

For saving this formbean to database use

private boolean saveOrUpdate(SolutionFormBean formbean) 
{
Session session = null;

//Transaction object
// Nothing happens without transaction in hibernate.
Transaction transaction = null;
try {
// This step will read hibernate.cfg.xml
// and prepare hibernate for use
SessionFactory sessionFactory = new Configuration()
.configure().buildSessionFactory();
session = sessionFactory.openSession();
// Using a transaction is mandatory.
transaction = session.beginTransaction();
session.saveOrUpdate(formbean);
// Commit it
transaction.commit();
System.out.println("Done");
return true;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
} finally {
// Actual row insertion will happen at this step
if(session!=null)
{
session.flush();
session.close();
}
return true;
}
}

While reading Blob from database, you would have to do the reverse, i.e.
convert Blob to byteArray and write to ServletOutputStream

Blob dbBlob = dbBean.getUploadedBlob();
int bloblength=(int)dbBlob.length();
byte[] tempByte = dbBlob.getBytes(1, bloblength);
// Now we have converted blob to byte array.
ServletOutputStream out = response.getOutputStream();
// For reading more about this header do check out the following link
// http://javakafunda.blogspot.com/2011/10/forcing-saveas-using-http-header.html
response.setHeader("Content-Disposition", "attachment; filename="
+formbean.getFilename());
out.write(tempByte);
out.flush();
out.close();

insert doesn’t works on hibernate??


Source : http://www.coderanch.com/t/219259/ORM/java/insert-doesn-work-hibernate

insert doesn’t work on hibernate

Hi,

Whenever I try to insert data through hibernate into DB, it displays all the steps executed but it doesn’t insert a new row into the database. Please tell me what could be the possible cause for this.

The code for my class is

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class FirstExample {

public static void main(String[] args) {
Session session = null;

try {
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
session.save(contact);
System.out.println("Done");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
// Actual contact insertion will happen at this step
session.flush();
session.close();

}

}
}

Nothing happens in a database without a transaction. Have a read of the linked Wiki entry and you should see how to fix this issue.

Below is the working code:

//Transaction object
Transaction transaction = null;

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
session.save(contact);
/*This bit ur missing*/
transaction.commit();
System.out.println("Done");
}

Column names in hbm.xml

When i added a field in my pojo class, with name xMoveCompatibleItem and I used eclipse’s inbuilt feature to generate getter and setter methods

Eclipse generated methods with the following names:
getXMoveCompatible()
setXMoveCompatible(String)

Note that X and M are both capital and consecutive, which was creating a problem for weblogic. It was not able to find the getter method for that property.

Do take care while adding a property, if the second letter of the property name is in CAPITAL

Premature end of file when running junits

Problem:

Premature end of file error when running Junits

[junitreport] [Fatal Error] :-1:-1: Premature end of file.
[junitreport] The file /tmp/repository/Yogesh/task2652_story1984/modulesmgr/junit_report/out/xml/TEST-com.coresecurity.ctrlsvc.modules.ModulesImportAndBasicCRUDTest.xml is not a valid XML document. It is possibly corrupted.

Observations:
1) TESTS-testsuites.xml was coming out to be empty.
2) The resulting xml file was getting too large in size.

Solution:
Hibernate logging was enabled which was leading to large size of XML.
We disabled logging in config.xml as given below
Earlier it was true, we made it false








org.hibernate.dialect.MySQL5InnoDBDialect
false
update
true
5
20
300
50
3000


How to connect Hibernate with Microsoft Access

1. Go to Control Panel
2. Go to Administrative Tools
3. Go to ODBC Data sources
4. Create a DSN (say mydb), give the path to .mdb file.
5. Get hibernate.jar

6. Extract contents of access.zip and get Access_JDBC30.jar

7. Create a new Java Project in NetBeans 6.7 or greater. and give the above 2 jars in classpath of the project

8. Create the employee class inside demo package with the following contents

package demo;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
*
* @author Yogi
*/
@Entity
public class Employee implements Serializable {
@Id
int empId;
String empIbu;
String empName;
int empSalary;


public Employee() {
}
public String toString()
{
return empName;
}
public Employee(int empId, String empIbu, String empName, int empSalary) {
this.empId = empId;
this.empSalary = empSalary;
this.empName = empName;
this.empIbu = empIbu;
}

public String getEmpIbu() {
return empIbu;
}

public void setEmpIbu(String empIbu) {
this.empIbu = empIbu;
}

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public int getEmpSalary() {
return empSalary;
}

public void setEmpSalary(int empSalary) {
this.empSalary = empSalary;
}

}

9. Create hibernate.cfg.xml in the root directory of the application (outside all packages)





com.hxtt.sql.access.AccessDriver
jdbc:odbc:mydb
com.hxtt.support.hibernate.HxttAccessDialect
<!-- Please note, here the value update is not working with MS-Access
Although it should work theoretically, but practically, the value
update is able to create the table for the first time
and after that it fails every time -->
create
true



10. Create EmployeeClient.java file inside client package (Though not mandatory)

/**
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package client;

import demo.Employee;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

/**
*
* @author Yogi
*/
public class EmployeeClient {
public static void main(String args[])
{
/* Here we have used AnnotationConfiguration because, we have used Annotations in
* Employee class to map the class fields with the table fields.
* If Employee.hbm.xml is used for this mapping then here we would have used
* Configuration (which we normally do)
*/

SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx=null;
try
{

Criteria c = session.createCriteria(Employee.class);
List l = c.list();
Iterator it = l.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
// Employee e = new Employee(234, "IVS", "Vinay", 6500);
// tx = session.beginTransaction();
// session.save(e);
// tx.commit();
// tx=null;
}
catch(HibernateException ex)
{
System.out.println("Exception occured : " + ex.getMessage());
}
finally
{
System.out.println("Closing the session");
session.close();
}
}
}

Please note the text in red in EmployeeClient class.
Here we have used AnnotationConfiguration because, we have used Annotations in Employee class to map the class fields with the table fields.
If Employee.hbm.xml is used for this mapping then here we would have used Configuration (which we normally do)

SessionFactory factory=new Configuration().configure().buildSessionFactory();