Thursday, September 15, 2011

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:

Problem
I had two objects Contacts and Groups having many-to-many association.
A Contact can belong to multiple Groups and a Group can contain multiple Contacts.
My objective was to return a set of Contacts along with the Groups they were associated with.

But if the Contacts-Groups association is set to Lazy load then the above exception will be thrown.

Solution
1. FetchType can be set to EAGER and everything will work fine, the Groups will be loaded; but in a more general case, where the graph of java objects can grow very large, the use of eager fetch may cause unnecessary data to be loaded and the application will be slowed down.

2. Another solution is to explicitly load any lazy-loading the required fields actually hitting a method on those properties
ex: contact.getEmailSet().size(). But this will result in subsequent sql firing which are required to load Groups (Child)
Will also slow down the system.

3. Another solution is to include "fetch join" which allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.





Contacts Domain Object:
@Entity
@Table(name = "Contacts")
public class Contacts implements java.io.Serializable
{
…..
…..
private Set emailSet = new HashSet(0);
….
….

@ManyToMany(targetEntity = EmailList.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch= FetchType.LAZY)
@JoinTable(name="Contacts_EmailGroup", joinColumns={@JoinColumn(name="contactsId")}, inverseJoinColumns={@JoinColumn(name="emailGroupId")})
public Set getEmailSet() {
return this.emailSet;
}
public void setEmailSet(Set emailSet) {
this.emailSet = emailSet;
}
}

EmailList Domain Object:
@Entity
@Table(name = "EmailGroup")
public class EmailList implements java.io.Serializable
{
….
….
private Set contacts = new HashSet(0);
….
….

@ManyToMany(targetEntity = Contacts.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy="emailSet")
public Set getContacts() {
return this.contacts;
}
public void setContacts(Set contacts) {
this.contacts = contacts;
}
}

DAO layer :
private EntityManager contactsEntity;


public List findAllContacts()
{
Query qry = contactsEntity.createQuery("FROM Contacts c left join fetch c.emailSet");
return qry.getResultList();
}



Hope the solution will be of some use :)

Thanks

A Solution to Hierarcy Cycle Problem with JSON: JSON Filter

When you have a cycle in your domain model, beacuse sometimes you realy need it*, then with Spring JsonView, indeed you may have same problem in different cases, while converting Java objects to JSON objects, you can get en error :

net.sf.json.JSONException: There is a cycle in the hierarchy!

with a following unusefull stack trace:)

First of all, think carefully fi you really do need this cycle in the dependency. If you don’t, remove it.
If you do, the you can use, JSON filters.

I will give an example code to show it. In the code, resulting JSON object will contain only id, name and description fields and values of the objects.




JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
if ("name".equals(name) || "description".equals(name) || "id".equals(name)) {
return false;
}
return true;
}
});
List jsonObjects = new ArrayList();
for (Object object : objects) {
jsonObjects.add(JSONSerializer.toJSON(object, config));
}
//Here you have jsonObjects, do whatever you need.
...


This is a sample code. It depends on you how to use this in a proper way! :)

* Consider, you have an class X with composition Y, and in Y class, if you need all Xs referenced by Y, then you will probably have a property containing list of X. Then you have cycle! For example, Employee works on a Department, so Employee has a composition with Department, in Department you need all employees workin in this department.

Wednesday, July 27, 2011

how to submit a Ext.form.Panel to a specified URL with params?

var panel = Ext.create('Ext.form.Panel', {
id: 'businessUnit-form',
url: 'createNewBusinessUnitForList.htm',
.....
....
.....
});

formCmp.getForm().submit({
method:'POST',
params:{
id: id,
status: status,
articles: aArticles
},
...
...
});

Tuesday, July 19, 2011

Thursday, July 7, 2011

Can you help me to do this? - extjs4.0.2a problem

Following I have given you the source code. There I am doing my update to the database by simply double click on the row and then when I am going to delete a record it will return a message as there have a data violation. up to this level the program is working in well manner.

But the problem is after that delete , if I go to update any record, the proxy executes update and then destroy(delete) again.

For your further ref -

when I remove some records from this store without page refreshing, it seems that all previous deleted items are stored somewhere and sended to servlet on every new update. When I refresh page, first update is ok, but any next update again after removing a record accumulate previous removed records. What I do wrong and how I can fix it?


====CODE====
============

/*

Ext JS 4.0.2a
*/

Ext.require(['Ext.data.*', 'Ext.grid.*', 'Ext.dd.*']);

Ext.define('StakeholderType', {
extend: 'Ext.data.Model',
fields: [{
name: 'stakeholderTypeId',
type: 'int',
useNull: false
}, 'code', 'description', 'sector']
});

Ext.data.proxy.Rest.override({
actionMethods : {
create : 'POST',
read : 'GET',
update : 'POST',
destroy: 'POST'
}
});

Ext.onReady(function(){

var jsonReader = Ext.create('Ext.data.reader.Json',{
root: 'data',
totalProperty: 'total',
successProperty: 'success',
idProperty: 'stakeholderTypeId',
messageProperty: 'message'
});

var jsonWriter = Ext.create('Ext.data.writer.Json',{
root: 'data',
encode: true,
writeAllFields: true
});

var proxy = Ext.create('Ext.data.proxy.Rest',{
api: {
read : 'stakeholderTypeView.htm',
update : 'stakeholderTypeEdit.htm',
destroy : 'stakeholderTypeDelete.htm'
},
reader : jsonReader,
writer : jsonWriter,
idProperty: 'stakeholderTypeId',
listeners: {
exception: function(proxy, response, operation){
Ext.MessageBox.show({
title: 'ERROR',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}

});

var store = Ext.create('Ext.data.Store', {
autoLoad : true,
autoSync : true,
model : 'StakeholderType',
proxy : proxy
});

var rowEditing = Ext.create('Ext.grid.plugin.RowEditing',{
clicksToEdit: 2
});

var grid = Ext.create('Ext.grid.Panel', {
plugins: [rowEditing],
width: 325,
height: 250,
frame: true,
title: 'Stakeholder Types',
store: store,
iconCls: 'item-agent',
columns: [{
header: document.getElementById("code").value,
width: 70,
sortable: false,
dataIndex: 'code'
}, {
header:document.getElementById("description").value,
width: 145,
sortable: true,
dataIndex: 'description',
editor: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: document.getElementById("sector").value,
width: 85,
sortable: false,
dataIndex: 'sector',
field: {
xtype: 'textfield'
}
}],
listeners: {
selectionchange: function(model, records) {

if (records[0]) {
this.up('form').getForm().loadRecord(records[0]);
}

}
},
dockedItems: [{
xtype: 'toolbar',
items: [{
text: document.getElementById("edit").value ,
iconCls: 'icon-user-add',
handler: function(){

var editS = grid.getView().getSelectionModel().getSelection()[0];
rowEditing.startEdit(editS,0);
}
}, '-', {
itemId: 'delete',
text : document.getElementById("remove").value,
iconCls: 'icon-user-delete',
disabled: false,
handler: function(){
var selection = grid.getView().getSelectionModel().getSelection()[0];
if(selection){
var con = confirm('Are you sure?');
if (con == true) {
grid.store.remove(selection);
grid.store.load({
scope : this,
callback: function(records, operation, success) {
//the operation object contains all of the details of the load operation
console.log(records);
}
});
}
}
}
}]
}]
});


var fieldSet = Ext.create('Ext.form.FieldSet',{
columnWidth: 1,
margin: '0 0 0 10',
title:'StakeholderType details',
width: 300,
labelWidth: 90,
defaultType: 'textfield',
items: [{
fieldLabel: 'Code',
width: 200,
disabled:true,
name: 'code'
},{
fieldLabel: 'Description',
disabled:true,
width: 250,
name: 'description'
},{
fieldLabel: 'Industrial Sector',
disabled:true,
width: 200,
name: 'sector'
}]
});

var panel = Ext.create('Ext.form.Panel', {
id: 'stakeholder-form',
frame: true,
title: 'Mapping Stakeholder',
bodyPadding: 5,
width: 650,
layout: 'column', // Specifies that the items will now be arranged in columns

fieldDefaults: {
labelAlign: 'left',
msgTarget: 'side'
},

items: [
grid,
fieldSet
],
renderTo: 'grid_to_form'
});

});

ExtJS, Spring MVC 3 and Hibernate 3.5: CRUD DataGrid Example

http://java.dzone.com/articles/extjs-spring-mvc-3-and?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+javalobby%2Ffrontpage+%28Javalobby+%2F+Java+Zone%29

Tuesday, July 5, 2011

GUI sample for grid panel with extjs 4.0.2a

Sample extjs code for creating a proxy between a data store at client side and backend.

extjs 4.0.2a example..

======This should be overriden globally for use ===============
Ext.data.proxy.Rest.override({
actionMethods : {
create : 'POST',
read : 'GET',
update : 'POST',
destroy: 'POST'
}
});
===============================================================

var jsonReader = Ext.create('Ext.data.reader.Json',{
root: 'data',
totalProperty: 'total',
successProperty: 'success',
idProperty: 'stakeholderTypeId',
messageProperty: 'message'
},StakeholderType);

var jsonWriter = Ext.create('Ext.data.writer.Json',{
root: 'data',
encode: true,
writeAllFields: true
});


var proxy = Ext.create('Ext.data.proxy.Rest',{
api: {
read : 'stakeholderTypeView.htm',
update : 'stakeholderTypeEdit.htm',
destroy : 'stakeholderTypeDelete.htm'
},
reader : jsonReader,
writer : jsonWriter
});

Do you have really tired of finding a well suited and speedy UI framework?

Then what about extjs 4.0.x???
It's a powerful framework with RESTful support.
Just try it..

http://edspencer.net/

What if distributed web application is deployed in container under multiple jvms when a client request is recieved?

Is it creating threads from each jvm for a one request?????


it's simple.... there u will be created multiple threads from each jvm but still there have only one servlet instance for the container. Are you sure this answer???
No problem if I am wrong becos u r the job finder..pls. google this now it self.

Tuesday, June 14, 2011

Spring-Hibernate major concerns for basics

@ManyToOne(cascade=CascadeType.PERSIST)
@ManyToOne(cascade=CascadeType.ALL)
@ManyToOne(cascade=CascadeType.MERGE)
@ManyToOne(cascade=CascadeType.REMOVE)
@ManyToOne(cascade=CascadeType.REFRESH)


@Transactional(propagation=Propagation.REQUIRED)
@Transactional(propagation=Propagation.SUPPORTS)

@RequestParam

Did you get the diff between when we are using hibernate solely and spring-hibernate as a combination?

Refer more...

There have many major differences with spring rather than normal hibernate.

Monday, June 13, 2011

what is the most special annotation for handling transactions in spring service layer?

@Transactional


And how should it be used when declaring read only and writing transactions?

@Service("businessUnitListService")
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public class BusinessUnitListServiceImpl implements BusinessUnitListService {


@Override
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public List getAllBusinessUnitList(Long businessUnitId) {
return businessUnitListDAO.getAllBusinessUnitList(businessUnitId);
}

@Override
@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public void deleteBusinessUnitList(String data) {
if (data.indexOf('[') > -1) {
List deleteBusinessUnitList = businessUnitListUtil.getListIdFromJSON(data);
for (Long id : deleteBusinessUnitList) {
businessUnitListDAO.deleteBusinessUnitList(id);
}
} else {
Long id = Long.parseLong(data.toString());
businessUnitListDAO.deleteBusinessUnitList(id);
}
}

}


if you missed out one of above annotation properly..

you will see only following sql statements on hibernate console
Hibernate: select businessun0_.BUSINESS_UNIT_ID as col_0_0_, businessun0_.CODE as col_1_0_, businessun0_.DESCRIPTION as col_2_0_ from transaction.BUSINESS_UNIT businessun0_
Hibernate: select nextval ('hibernate_sequence')

but data will not be inserted when it is a insert query..
if it was configured correctly.

you will see
Hibernate: select businessun0_.BUSINESS_UNIT_ID as col_0_0_, businessun0_.CODE as col_1_0_, businessun0_.DESCRIPTION as col_2_0_ from transaction.BUSINESS_UNIT businessun0_
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into transaction.BUSINESS_UNIT_LIST (BUSINESS_UNIT_ID, CODE, DESCRIPTION, VERSION_ID, BUSINESS_UNIT_LIST_ID) values (?, ?, ?, ?, ?)

How do you define Spring based Junit classs?

@ContextConfiguration(locations="file:src/test/resources/ApplicationContext.xml")
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public class BusinessUnitListServiceImplTest extends AbstractTransactionalJUnit38SpringContextTests{
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
protected void setUp() throws Exception {
super.setUp();
}

@After
protected void tearDown() throws Exception {
super.tearDown();
}

public void testAddBusinessUnitList(){
//your unit testings
}
}

Thursday, June 9, 2011

what are the objects types of hibernate?

1. Transient
2. Persistence
3. Detached

can final variable be assigned a value at runtime or compile time?

cannot

How can there be existed more than one object at runtime even we have used singleton pattern?

with "Reflection" it can be done.
http://en.wikipedia.org/wiki/Reflection_%28computer_science%29

I think I guess correctly but you are the decider which is the correct one????
hik hik....

just google it and find the answer.


code for learn something

public class A {

private static A a = null;

//singleton pattern
public static A getInstance(){
if(a==null)
a = new A();
return a;
}

void m(String msg){
System.out.println(msg);
}

public static void main(String[] args) {
A a = getInstance();
A.B b = a.new B();
a.m("m from A");
b.x(a);
}

class B{
void x(A a){
A t = A.getInstance();
t.m("x from B");
System.out.println("Both of objects are the same one? "+t.equals(a));
}
}

}

what is IOC and DI?

dependency injection is the passing or setting of dependencies into a software component.

DI is the most specific pattern of IOC.

want to know more -
follow this';;
http://martinfowler.com/articles/injection.html

The diff between jsp and servlet

JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.




for more about jsp and servlets:::
http://www.javacertificate.net/jsp_iqns.htm

what are the autowiring scopes in spring?

just check here;;;

http://www.visualbuilder.com/java/spring/tutorial/autowiring-in-spring/

what is the treeSet in java?

This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.

java.lang.Object
extended by java.util.AbstractCollection
extended by java.util.AbstractSet
extended by java.util.TreeSet

For further reference:::::::

http://www.esus.com/docs/GetQuestionPage.jsp?uid=821

Java Dictionary and Collection API

Logical question- how can we handle corrupted xml errors or invalid data?

How can we handle errors which happening at run time when parsing an XML document through a web service? How can we detect specified error when XML was crashed or with invalid escape characters and keep record of that error to inform user?

?????????
?????
???
??
?

I guess the answer is here...
http://www.ibm.com/developerworks/library/x-saxerror/index.html

Diff of SAX and DOM

What is a transaction? what are the properties of a database transaction?

A transaction is an agreement, communication, or movement carried out between separate entities or objects,

ACID properties are related to database transaction.
1)atomic
2)consistent
3)isolated
4)durable

Difference between DTO and DAO...

DTO means Data Transfer Objects equivalent to POJO classess(Java beans) those are carrying data.

DAO means Data Access Objects those are doing CRUD operations with DTOs or DB

finally block

public class A {
public static void main(String[] args) {
System.out.println(new A().m());
}

public int m(){
try {
throw new Exception();
} catch (Exception e) {
return 0;
}finally{
return 1;
}
}
}

what will be the output of this????

Let's try to build scrum masters/project managers/software architects/even a company with training AI models

The concept: The basic concept is to build trained AI model for each role separately in scalable fashion within a private cloud. As an examp...