I want to create a method thats called createTransaction that will commit the transaction if its success, but roll back all the transaction in some table if its failed. On the other side, I want to save the transaction log into db even if its failed or succeed.
I’ve tried this code, but when I try enter a customerId thats not saved in db, the transaction should be rolled back the transaction, product, and customer entity, but It still commit the transaction in product table. Can someone explain me whats going on and give me the solution for this?
public String createTransactionWithLog(TR_Transaction transaction) {
String message = "";
try {
boolean successTransaction = createTransaction(transaction);
if(successTransaction == true) {
message = "Transaksi sukses";
}else {
message = "Transaksi gagal";
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
Activity_Log log = new Activity_Log(LocalDateTime.now(), "DoTransaction", message);
activityLogRepository.save(log);
}
return message;
}
#Transactional
public boolean createTransaction(TR_Transaction transaction) {
long productId = transaction.getProductId();
long customerId = transaction.getCustomer().getCustomerId();
MS_Product product = productRepository.getOne(productId);
MS_Customer customer = customerRepository.getOne(customerId);
if(product == null || customer == null) {
return false;
}else {
transaction.setCustomer(customer);
int newProductStock = product.getProductStock() - transaction.getQuantity();
product.setProductStock(newProductStock);
transaction.setProductPrice(newProductStock);
customer.getTransactions().add(transaction);
TR_Transaction savedTransaction = transactionRepository.save(transaction);
MS_Customer updatedCustomer = customerRepository.save(customer);
MS_Product updatedProduct = productRepository.save(product);
return true;
}
}
Related
in the following code i want to Update record As you see SaveChanges() call when i get the First 'q' . but after run the code and get the first and only record for the one to Update, i get the success returned 2. the problem is after saveChanges i have 2 records in Sal Table. what should i write for define q until I get int success just 1 . and update clearly.
public static bool UpdateUser(User user)
{
try
{
var q = db.Users.Where(x => x.UserName == user.UserName).**FirstOrDefault**();
if (q != null)
{
q.Password = user.Password;
db.Users.Update(user);
int *success* = db.SaveChanges();
if (success == 1)
{
return true;
}
else
{
return false;
}
}
return false;
}
catch (Exception ex)
{
throw ex;
}
}
You're using "Connected scenario" of EF in your code.
in this case dbset that you fetching data from, tracking and EF listening to your changes for the data getting from dbset, then, after any changes to this datas when you using "SaveChanges" update them.
for resolve that You can use db.User.AsNoTracking().... to say to EF that i not needed to track dbset!
I have a spring boot program and right now my PutMapping function seems not be working as expected. Right now if I update the field in postman it says no errors but when I checked to see if the update occurred then there are no changes.
Controller:
#PutMapping(path = "{bookingId}")
public void updateBooking (
#PathVariable("bookingId") Long bookingId,
#RequestParam(required = false) Integer tickets ) {
bookingService.updateBooking(bookingId, tickets);
}
Service:
public void updateBooking(Long bookingId, Integer tickets) {
// checks if event id exists
Booking booking = bookingRepository.findById(bookingId).orElseThrow(() -> new IllegalStateException(
"Booking with id " + bookingId + " does not exists. "));
if (tickets != null && !Objects.equals(booking.getTickets(), tickets)) {
booking.setTickets(tickets);
booking.setAmount(booking.getAmount());
}
else {
throw new IllegalStateException(
"The update was unsuccessful" );
}
}
Model:
public Integer getTickets() {
return tickets;
}
public void setTickets(Integer tickets) {
this.tickets = tickets;
}
You are not saving the updated object in the database.
public void updateBooking(Long bookingId, Integer tickets) {
// checks if event id exists
Booking booking = bookingRepository.findById(bookingId).orElseThrow(() -> new IllegalStateException(
"Booking with id " + bookingId + " does not exists. "));
if (tickets != null && !Objects.equals(booking.getTickets(), tickets)) {
booking.setTickets(tickets);
booking.setAmount(booking.getAmount());
// save the updated booking in the database
bookingRepository.save(booking)
}
else {
throw new IllegalStateException(
"The update was unsuccessful" );
}
}
public static void insertInboundJive(Map<Id, String> mapCases){
try{
system.debug('Aditya');
Map<Id, String> mapCases1 = new Map<Id, String>();
Map<Id, Integer> mapIncrements = new Map<Id, Integer>();
//List<ICS_Case_Interaction__c> lstCaseInteraction;
if(mapCases != null && mapCases.size() > 0) {
List<ICS_Case_Interaction__c> lstCaseInteraction = [ SELECT Id,case__r.origin FROM ICS_Case_Interaction__c Where case__r.Id =:mapCases.keySet()];
for(ICS_Case_Interaction__c caseInteracts :lstCaseInteraction ){
if(caseInteracts.case__r.Id != null && caseInteracts.case__r.Status == 'New Customer Message'){
system.debug('**AdityaDebug**' +caseInteracts.case__r.Id);
system.debug('**AdityaDebug**' +caseInteracts.case__r.Status);
mapcases1.put(caseInteracts.case__r.Id , TYPE_JIVE_INBOUND);
Integer intIncrement = mapIncrements.get(caseInteracts.case__r.Id);
system.debug('Increment' +intIncrement);
if(intIncrement != null){
intIncrement++;
system.debug('Increment++' +intIncrement);
}
else {
intIncrement = 1;
}
mapIncrements.put(caseInteracts.case__r.Id, intIncrement);
}
}
if(mapCases.size() > 0) {
insertByCaseAsync(mapCases, mapIncrements);
}
}
}
catch(Exception ex){
Core_Log_Entry.logEntryWithException('Case Interaction Metrics', 'CaseInteraction','insertInboundEmail', 'Error', null, null, ex);
}
}
This is my Method in the class.I am trying to call the apex method in the trigger.but its throwing the error.Could you please help me and try to reach out the best.
The error which I am getting was
line 188, col 106. Method does not exist or incorrect signature: void insertInboundJive(List) from the type ICS_Case_Interactions_Trigger_Handler
if(trigger.isUpdate) {
if(Label.ICS_Case_Interaction_Metrics.equals('1')) {ICS_Case_Interactions_Trigger_Handler.insertInboundJive(trigger.new);}
}
You are trying to pass the wrong parameters. In the method you have defined that when called you need to pass a Map where the values are String however you are passing Trigger.new which is a list of Objects. My approach is to handle the mapping in the trigger and then manipulate data in the controller:
In this case you can do the below to pass the records and get the string of data you want in the controller.. or do it in the trigger so you don't change the controller.
Map<Id,Contact> map = new Map<Id,ICS_Case_Interaction__c>(); // new map
for(ICS_Case_Interaction__c con :trigger.new){
map.put(con.Id, con); // enter the records you need for the method
}
if(trigger.isUpdate) {
if(Label.ICS_Case_Interaction_Metrics.equals('1')) {
ICS_Case_Interactions_Trigger_Handler.insertInboundJive(map);
}
}
and in the controller you should have
public static void insertInboundJive(Map<Id, ICS_Case_Interaction__c> mapCases){
}
I have an activity that is being swapped out when I raise an intent for another activity. onPause calls saveState() to save work so far:
private void saveState() {
...
...
if (myUri == null) {
// Inserting a new record
*** myUri = getContentResolver().insert(ContentProvider.CONTENT_URI, values);
} else {
// Update an existing record
getContentResolver().update(myUri, values, null, null);
}
}
Before calling getContentResolver(), ContentProvider.CONTENT_URI = 'content://nz.co.bkd.extraTime.contentprovider/times'.
After the call, myUri = 'times/#' where #=row ID. My question is; where is the 'content:...' prefix to the returned uri?
During the call, ContentResolver.java is called and returns CreatedRow uri
ContentResolver.java
....
....
public final Uri insert(Uri url, ContentValues values)
{
IContentProvider provider = acquireProvider(url);
if (provider == null) {
throw new IllegalArgumentException("Unknown URL " + url);
}
try {
long startTime = SystemClock.uptimeMillis();
*** Uri createdRow = provider.insert(url, values);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "insert", null /* where */);
return createdRow;
} catch (RemoteException e) {
// Arbitrary and not worth documenting, as Activity
// Manager will kill this process shortly anyway.
return null;
} finally {
releaseProvider(provider);
}
}
At this point, createdRow = 'times/#'.
The record does actually get saved in the Sqlite database.
Do I have to add the uri prefix in my code or should the full uri be returned?
I've written a program that takes care of registration and each time i try to insert multiple new users at a time with different id it gives the error message:
java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL130217122630580' defined on 'STCEPARTICIPANTS'.
here is the action passed from a button WHICH instructs the data to be saved:
private void printsavebtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String query1= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query2= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query3= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query4= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String [] queryarray= {query1,query2,query3,query4};
int speno1,speno2,speno3,speno4;
String task;
if(fname1tf.getText().equals("")||sname1tf.getText().equals("")||speno1tf.getText().equals("")
||uni1cb.getSelectedItem().equals("-")|| fname2tf.getText().equals("")||sname2tf.getText().equals("")||speno2tf.getText().equals("")
||uni2cb.getSelectedItem().equals("-") || fname3tf.getText().equals("")||sname3tf.getText().equals("")||speno3tf.getText().equals("")
||uni3cb.getSelectedItem().equals("-") || fname4tf.getText().equals("")||sname4tf.getText().equals("")||speno4tf.getText().equals("")
||uni4cb.getSelectedItem().equals("-") ){
JOptionPane.showMessageDialog(rootPane, "Please enter the fields marked '*'");
}
else {
try{
speno1=Integer.parseInt(speno1tf.getText());
speno2=Integer.parseInt(speno2tf.getText());
speno3=Integer.parseInt(speno3tf.getText());
speno4=Integer.parseInt(speno4tf.getText());
int [] taskit = {speno1,speno2,speno3,speno4};
for(int count2=0;count2<taskit.length;count2++){
task= "select * from STCEPARTICIPANTS where spe_number="+taskit[count2];
DBOptions.executeNonQuery(queryarray[count2]);
if(SearchData.searchSpeno(task)==true){
JOptionPane.showMessageDialog(rootPane, "Sorry, this member is already in the database./t Please go to Profile to renew of view membership details. Thank you!");
}
}
the class SearchData is given below:
public static boolean searchSpeno(String task){
String query =task;
ResultSet rs = DBOptions.executeSQLQuery(query);
if(rs!=null)
{
try
{
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
if(colCount > 0)
{
try
{
if(rs.next() && ! rs.getString("spe_number").equals(""))
{
return true;
}
else
{
return false;
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, e,"Search Error", 3);
return false;
}
}
else
{
//JOptionPane.showMessageDialog(null, "Invalid Employee ID","Search Error", 3);
return false;
}
}
catch(SQLException ex)
{
//JOptionPane.showMessageDialog(null, ex.getMessage(),"Error Occured", 2);
return false;
}
}
else
{
return false;
}
}
}
}
the class DBOptions is :
public static boolean executeNonQuery(String sqlString)
{
try
{
Statement stmt = con.createStatement();
stmt.executeUpdate(sqlString);
JOptionPane.showMessageDialog(null,"success!");
return true;
//return the number of rows affected
}
catch(SQLException e)
{
//display error message
JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Non Query Execution Failure", 1);
e.printStackTrace();
return false;
}
}
public static ResultSet executeSQLQuery(String sqlQuery)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeQuery(sqlQuery); //query successfully executed
}
catch(SQLException e)
{
//display error message
JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Query Execution Failure", 1);
return null; //sql query execution failed
}
}
}
Please, i have seen some problems like this and i have tried the different forms of solution but no head way. I need to get this ready for a mini project defense. I appreciate your response. Thank you.
How did you create the table? Can you paste the CREATE TABLE statement into your question?
Each row in your table must have a unique value for each column which is defined either as PRIMARY KEY or as UNIQUE, and Derby is enforcing that constraint.
Go back to your table definition, figure out for which columns you have specified either PRIMARY KEY or UNIQUE on the column, and then look at your program to figure out what values you are providing for those columns.
Then modify your program so that it provides a unique value for each such column.