Fórum

Service Builder: Update data if exist, insert if not exist

SHI HONG CHIN, modificado 7 Anos atrás.

Service Builder: Update data if exist, insert if not exist

New Member Postagens: 2 Data de Entrada: 16/05/15 Postagens Recentes
I am using Service Builder. My Liferay version is 6.2.

Assume that there is an entity "ABC" with a primary key.

Assume that I use the following codes to do update or insert (Someone call it "UPSERT"):


ABC abc;
try{
	//Get ABC by using primary key value, and then update a column value.
	abc = ABCLocalServiceUtil.getABC(primarykeyvalue);
	abc.setCol1("value");
	ABCLocalServiceUtil.updateABC(abc);
} catch (NoSuchABCException e){
	// If the primary key value not exist in the database table, insert it.
	abc = ABCLocalServiceUtil.createABC(primarykeyvalue);
	abc.setCol1("value");
	ABCLocalServiceUtil.addABC(abc);
}


The exception class and all functions in the above sample code are generated by service builder.

The update and insert operation was success, even when the primary key value not exist in the database table. However, if the primary key value does not exist, there is a warning message "No ABC exists with primary key ....." on server.

I don't want the server to log or display the warning message above. So, what is your recommendation? I am willing to edit my source code.
thumbnail
Juan Gonzalez, modificado 7 Anos atrás.

RE: Service Builder: Update data if exist, insert if not exist

Liferay Legend Postagens: 3089 Data de Entrada: 28/10/08 Postagens Recentes
SHI HONG CHIN:
I am using Service Builder. My Liferay version is 6.2.

Assume that there is an entity "ABC" with a primary key.

Assume that I use the following codes to do update or insert (Someone call it "UPSERT"):


ABC abc;
try{
	//Get ABC by using primary key value, and then update a column value.
	abc = ABCLocalServiceUtil.getABC(primarykeyvalue);
	abc.setCol1("value");
	ABCLocalServiceUtil.updateABC(abc);
} catch (NoSuchABCException e){
	// If the primary key value not exist in the database table, insert it.
	abc = ABCLocalServiceUtil.createABC(primarykeyvalue);
	abc.setCol1("value");
	ABCLocalServiceUtil.addABC(abc);
}


The exception class and all functions in the above sample code are generated by service builder.

The update and insert operation was success, even when the primary key value not exist in the database table. However, if the primary key value does not exist, there is a warning message "No ABC exists with primary key ....." on server.

I don't want the server to log or display the warning message above. So, what is your recommendation? I am willing to edit my source code.


Use fetchABC method instead of getABC, and check if abc object is null or not. If it is null, it doesn't exist.