Eclipse throws me an exception - Duplicate entry '201805091-1' for key 'PRIMARY'. I understand that exception, but I do not understand why the code below makes a new record in my database. I thought this should work like: If the combination of date and doctors id does not exist - then make it otherwise use the combination that is currently in database. But there must be obviously something wrong...
Thank you very much :)
OperationsDate od = null; // these 6 lines of the code may be problematic
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
public void process(List<Integer> list, int doctorId, String pin, boolean inf) {
Patient p = em.find(Patient.class, pin);
Doctor d = em.find(Doctor.class, doctorId);
p.addDoctor(d);
d.addPatient(p);
int id = countId(doctorId);
OperationsDate od = null;
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
if(inf) {
for(int number : list) {
Medicine m = em.find(Medicine.class, number);
od.setDoctor(d);
d.addOperationsDate(od);
od.addMedicine(m);
m.addOperationsDate(od);
}
} else {
Operation o = em.find(Operation.class, list.get(0));
od.setDoctor(d);
d.addOperationsDate(od);
od.addOperation(o);
o.addOperationsDate(od);
}
}
public int countId(int doctorId) {
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
String id = "";
String date2 = date.toString();
for(int i=0; i < date2.length();i++) {
if(i == 4 || i == 7) {
continue;
}
id += date2.charAt(i);
}
id += doctorId;
int id2 = Integer.parseInt(id);
return id2;
}
Just try it this way then, as I told you in my comment:
OperationsDate od = em.find(OperationsDate.class, id);
if( od == null) {
od = new OperationsDate(id);
}
...
// potential persist or merge, depending on your frameworks configuration regarding autocommit and such
em.persist(od);
If it still doesn't work, add the code for your entities, to make sure nothing's wrong about it.
Related
How can I map the data to four values for the BalanceDTO instead of two like in the example I made for the NetDTO. Any help will be appreciated, I want to find the 4 values to map them. I just need help in the loop to find the values. Thanks in Advance.
/// 2 values CSV File
public void toCSVFile(List<ReceivedData> receivedDataList) {
logger.info("Executing net value strategy...");
List<ReceivedData> secondaryList = receivedDataList;
List<NetDTO> netDTOList = new ArrayList<>();
//maps data to netDTO, finds minuend and subtrahend
for (ReceivedData y : receivedDataList) {
for (ReceivedData x : secondaryList) {
if (y.getLotid().equals(x.getLotid()) && y.getMaterialNumber().equals(x.getMaterialNumber()) && y.getOperKey().equals(x.getOperKey()) && y.getOrderID().equals(x.getOrderID()) &&
y.getSerialID().equals(x.getSerialID()) && y.getStepKey().equals(x.getStepKey()) &&
!y.getDataCollectionID().equals(x.getDataCollectionID()) && y.getType().equals("MINUEND") && x.getType().equals("SUBTRAHEND")) {
NetDTO netDTO = new NetDTO(y, x);
netDTOList.add(netDTO);
}
}
}
writer(receivedDataList.get(0).getProcess().getProcessName() + ".csv", netDTOList);
}
///// Net DTO
public NetDTO(ReceivedData minuend, ReceivedData subtrahend) {
this.ordNumber = minuend.getOrdNumber();
this.matNumber = minuend.getMaterialNumber();
this.operator = minuend.getOperator();
this.serialNumber = minuend.getSerialNumber();
this.toolNo = minuend.getToolNo();
this.timeStamp = minuend.getTimeStamp();
this.dcTitleMinuend = minuend.getDcTitle();
this.dcValueMinuend = minuend.getDcValue();
this.dcTitleSubtrahend = subtrahend.getDcTitle();
this.dcValueSubtrahend = subtrahend.getDcValue();
}
//// Balance DTO (I want to map the data like I did in the netDTO to this dto. But with 4 values)
public BalanceDTO(ReceivedData value1, ReceivedData value2, ReceivedData value3, ReceivedData value4) {
this.ordNumber = value1.getOrdNumber();
this.matNumber = value1.getMaterialNumber();
this.operator = value1.getOperator();
this.serialNumber = value1.getSerialNumber();
this.toolNo = value1.getToolNo();
this.timeStamp = value1.getTimeStamp();
this.dcTitleValue1 = value1.getDcTitle();
this.dcValueValue1 = value1.getDcValue();
this.dcTitleValue2 = value2.getDcTitle();
this.dcValueValue2 = value2.getDcValue();
this.dcTitleValue3 = value3.getDcTitle();
this.dcValueValue3 = value3.getDcValue();
this.dcTitleValue4 = value4.getDcTitle();
this.dcValueValue4 = value4.getDcValue();
}
I wan to know how can I approach the looping when it comes 3 or more values. In this case, 4 values.
I have a whole bunch of rows that contain tax payments.
Each row contains PaymentDueDate.
If row is missing in between PaymentDueDates, I have to use same values from previous row to aggregate for all totals.
In below example, between Row="2" and Row="3", data is missing for months 2015/09, 2015/10, 2015/11, 2015/12, 2016/01, 2016/02.
So, I have to use Row="2" values to use to account for missing rows.
<PaymentChangeMaintenance>
<PaymentChangeMaintenanceTransaction Row="1">
<BuydownSubsidyAmount>0.00</BuydownSubsidyAmount>
<AnnualInterestRate>4.75000</AnnualInterestRate>
<PIAmount>689.79</PIAmount>
<PaymentDueDate>2015-07-01</PaymentDueDate>
<CityTaxAmount>23.22</CityTaxAmount>
<CountyTaxAmount>32.25</CountyTaxAmount>
</PaymentChangeMaintenanceTransaction>
<PaymentChangeMaintenanceTransaction Row="2">
<BuydownSubsidyAmount>0.00</BuydownSubsidyAmount>
<AnnualInterestRate>4.75000</AnnualInterestRate>
<PIAmount>689.79</PIAmount>
<PaymentDueDate>2015-08-01</PaymentDueDate>
<CityTaxAmount>125.25</CityTaxAmount>
<CountyTaxAmount>666.22</CountyTaxAmount>
</PaymentChangeMaintenanceTransaction>
<PaymentChangeMaintenanceTransaction Row="3">
<BuydownSubsidyAmount>0.00</BuydownSubsidyAmount>
<AnnualInterestRate>4.75000</AnnualInterestRate>
<PIAmount>689.79</PIAmount>
<PaymentDueDate>2016-03-01</PaymentDueDate>
<CityTaxAmount>125.25</CityTaxAmount>
<CountyTaxAmount>666.22</CountyTaxAmount>
</PaymentChangeMaintenanceTransaction>
</PaymentChangeMaintenance>
Here is code someone wrote, but it is not clean-looking. I would like to use for-each :/
private void aggregateEscrowPaymountAmounts(List<PaymentChangeMaintenanceFieldsV214Type> fieldsType,
PaymentChangeMaintenance paymentChangeMaintenance, final int numberOfTrialPayments) {
AtomicInteger cnt = new AtomicInteger(1);
Iterator<PaymentChangeMaintenanceFieldsV214Type> fieldsTypeIterator = fieldsType.iterator();
PaymentChangeMaintenanceFieldsV214Type fieldType = fieldsTypeIterator.next();
PaymentChangeMaintenanceFieldsV214Type nextFieldType = null;
if (fieldsTypeIterator.hasNext()) {
nextFieldType = fieldsTypeIterator.next();
}
LocalDate monthDate = fieldType.getNextPaymentDueDate();
while (cnt.getAndIncrement() <= numberOfTrialPayments) {
PaymentChangeMaintenance tempPaymentChangeMaintenance = createPaymentChangeMaintenanceEscrow(fieldType);
paymentChangeMaintenance.aggregate(tempPaymentChangeMaintenance);
monthDate = monthDate.plusMonths(1);
if (nextFieldType != null) {
LocalDate nextFieldTypeDate = nextFieldType.getNextPaymentDueDate();
if (nextFieldTypeDate.getMonthValue() == monthDate.getMonthValue()) {
fieldType = nextFieldType;
if (fieldsTypeIterator.hasNext()) {
nextFieldType = fieldsTypeIterator.next();
} else {
nextFieldType = null;
}
}
}
}
}
For this certain case you can use a following approach: determine a step - for you it's a month. Then initialize a default value for a case of absence of the value on the next step. Then use some method that will take a next value and default value and depends on a step presence will return one of them
Here is a pseudocode:
List<Item> items;
Item nextItem = items.get(0);
Value step = month;
for (int i = 1; i < items.size(); i++) {
nextItem = getNextItem(items.get(i), nextItem, step);
****
}
Item getNextItem(Item nextItem, Item defaultItem, Value step) {
if (!nextItem.getStepValue().equals(calcNext(step))) {
return defaultItem;
} else {
return nextItem;
}
}
StepValue calcNext(Value step) {
/*some calculations. In your case month increment*/
}
I really tried searching for the solution to this problem, but I cant seem to get it right. I have an application that Im working on, and I would like to print out all of a customers orders in a JTable with rows. So if a customer has three orders I want it to show each order on a separate row.
With this code (the next block) I got it to work, but it's only printing out the last value. So if I have Order 3 attached to a customer, and then add Order 4, it only shows Order 4.
JButton btnHämtaKund = new JButton("Hämta");
btnHämtaKund.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchTerm = sökrutaKund.getText();
Customer c = Controller.findCustomer(searchTerm);
String sum = "";
if (c != null) {
if (c.getOrders() != null) {
for (Order tmp : c.getOrders().values()) {
String date = tmp.getDate();
String price = Double.toString(tmp.getPrice());
String rfd = "";
if (tmp.getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (tmp.getRdyForDelivery() == false) {
rfd = "Processing";
}
model.addRow(new String[] {date, price, rfd});
}
txtfieldTestKund.setText(sum);
} else {
txtfieldTestKund.setText("c.getOrders() == null");
}
} else {
txtfieldTestKund.setText("c == null");
}
}
});
Model is my DefaultModelTable.
I also tried with a for-loop like this in case I was overwriting my last row all the time:
for (int i = 0; i < c.getOrders().size(); i++) {
String date = c.getOrders().get(i).getDate();
String price = Double.toString(c.getOrders().get(i).getPrice());
String rfd = "";
if (c.getOrders().get(i).getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (c.getOrders().get(i).getRdyForDelivery() == false) {
rfd = "Processing";
}
Object row[] = {date, price, rfd};
model.addRow(row);
}
but that just gave a Nullpointerexception.
Any ideas what to do? Really thankful for help!
I had to fix a method to increase the key for each Order i added to Customer, looks like I was overwriting the previous with the last one.
private int counter = 0;
public void add(Order o) {
counter += 1;
String newCounter = Integer.toString(counter);
this.orders.put(newCounter, o);
}
I'm currently workin' on a sales module using java+hibernate+oracle... I'm done with my order form in my jsp like this:
I'm getting my parameters doing this:
ArrayList<String> idMercaderias = new ArrayList<String>();
ArrayList<String> cantidades = new ArrayList<String>();
ArrayList<String> precios = new ArrayList<String>();
for (int k = 0; k < 10; k++) {
idMercaderias.add(request.getParameter("idMercaderia" + k));
cantidades.add(request.getParameter("cantidad" + k));
precios.add(request.getParameter("precio" + k));
}
I have 10 rows on my order detail, so I made the for, where my inputs are input1, input2, input3, etc. These are attributes of my object Mercaderia so i need to set them up, since they're on lists:
First I'm filtering the first list to avoid repeated articles:
Iterator itra = idMercaderias.listIterator();
ArrayList<String> sortedListIdMercaderias = new ArrayList<String>();
Object m;
while (itra.hasNext()) {
m = itra.next();
if (!sortedListIdMercaderias.contains(m)) {
sortedListIdMercaderias.add((String) m);
}
}
Now I create my object to set all the attributes:
DetallePedido detalle = new DetallePedido();
Now I'm doing a cycle 10 times (thinking of all rows in my form) and start to iterate each list to get my object attributes avoiding null or empty entries.
for (int x = 0; x < sortedListIdMercaderias.size(); x++) {
Iterator itr = idMercaderias.listIterator();
while (itr.hasNext()) {
String mercaderia = (String) itr.next();
if ((mercaderia != null) && (!mercaderia.equals(""))) {
Mercaderia mercaderiaSeleccionada = new MercaderiaDAO().findById(Integer.parseInt(mercaderia));
detalle.setMercaderia(mercaderiaSeleccionada);
}
}
Iterator itr2 = cantidades.listIterator();
while (itr2.hasNext()) {
String cantidad = (String) itr2.next();
if ((cantidad != null) && (!cantidad.equals(""))) {
int cantidadMercaderiaSeleccionada = Integer.parseInt(cantidad);
detalle.setCantidad(cantidadMercaderiaSeleccionada);
}
}
Iterator itr3 = precios.listIterator();
while (itr3.hasNext()) {
String precio = (String) itr3.next();
if ((precio != null) && (!precio.equals(""))) {
BigDecimal precioMercaderiaSeleccionada = new BigDecimal(precio);
detalle.setPrecioUnitario(precioMercaderiaSeleccionada);
}
}
Finally i just persist to my database:
Session session = new DetallePedidoDAO().getSession();
Transaction tx = session.beginTransaction();
try {
session.saveOrUpdate(detalle);
tx.commit();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't know why in the database i only get 1 row inserted (the last one with valid data) instead of all of them.
Any help will be really apreciated, this is for my final test in university project.
You've only ever got one DetallePedido object. You're changing its field values over and over in the various loops, but it's still just one object. Lastly you're saving it. Just once. Naturally, you only get one row inserted in your database.
What you could try is, instead of iterating through your Mercaderia objects, your Cantidad objects and your Precio objects separately; have a single loop that WITHIN EACH ITERATION creates a new DetallePedido object, sets the Mercaderia, the Cantidada and the Precio, and then saves the DetallePedido.
So, following the clues by David Wallace I made some tweaks to the idea and created an object WrapperDetallePedido like this:
public class WrapperDetallePedido {
int idMercaderia;
int cantidad;
double precio;
public int getIdMercaderia() {
return idMercaderia;
}
public void setIdMercaderia(int idMercaderia) {
this.idMercaderia = idMercaderia;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
}
Then in my Controller I created a single ArrayList and set my DetallePedido attributes:
ArrayList<WrapperDetallePedido> listado = new ArrayList<WrapperDetallePedido>();
for (int k = 0; k < 10; k++) {
if (!request.getParameter("idMercaderia" + k).equals("")){
WrapperDetallePedido WDetallePedido = new WrapperDetallePedido();
WDetallePedido.setIdMercaderia(Integer.parseInt(request.getParameter("idMercaderia" + k)));
WDetallePedido.setCantidad(Integer.parseInt(request.getParameter("cantidad" + k)));
WDetallePedido.setPrecio(Double.parseDouble(request.getParameter("precio" + k)));
listado.add(WDetallePedido);
}
}
Finally used Iterator for the previous list and set all the items from listado and persist to the database:
for (Iterator iterador = listado.listIterator(); iterador.hasNext();) {
WrapperDetallePedido detalle = (WrapperDetallePedido) iterador.next();
Mercaderia mercaderiaSeleccionada = new MercaderiaDAO().findById(detalle.getIdMercaderia());
DetallePedido detallePedido = new DetallePedido();
detallePedido.setMercaderia(mercaderiaSeleccionada);
detallePedido.setCantidad(detalle.getCantidad());
detallePedido.setPrecioUnitario(new BigDecimal(detalle.getPrecio()));
detallePedido.setPedidos(pedidoGenerado);
Session session1 = new DetallePedidoDAO().getSession();
Transaction tx1 = session1.beginTransaction();
new DetallePedidoDAO().save(detallePedido);
try {
session1.saveOrUpdate(detallePedido);
tx1.commit();
session1.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Finally got all my rows inserted as i needed... Thank you!
I am trying to convert a Java function into equivalent Groovy code, but I am not able to find anything which does && operation in loop. Can anyone guide me through..
So far this is what I got
public List getAlert(def searchParameters, def numOfResult) throws UnsupportedEncodingException
{
List respList=null
respList = new ArrayList()
String[] searchStrings = searchParameters.split(",")
try
{
for(strIndex in searchStrings)
{
IQueryResult result = search(searchStrings[strIndex])
if(result!=null)
{
def count = 0
/*The below line gives me error*/
for(it in result.document && count < numOfResult)
{
}
}
}
}
catch(Exception e)
{
e.printStackTrace()
}
}
My Java code
public List getAlert(String searchParameters, int numOfResult) throws UnsupportedEncodingException
{
List respList = null
respList = new ArrayList()
String[] searchStrings = searchParameters.split(",")
try {
for (int strIndex = 0; strIndex < searchStrings.length; strIndex++) {
IQueryResult result = search(searchStrings[strIndex])
if (result != null) {
ListIterator it = result.documents()
int count = 0
while ((it.hasNext()) && (count < numOfResult)) {
IDocumentSummary summary = (IDocumentSummary)it.next()
if (summary != null) {
String docid = summary.getSummaryField("infadocid").getStringValue()
int index = docid.indexOf("#")
docid = docid.substring(index + 1)
String url = summary.getSummaryField("url").getStringValue()
int i = url.indexOf("/", 8)
String endURL = url.substring(i + 1, url.length())
String body = summary.getSummaryField("infadocumenttitle").getStringValue()
String frontURL = produrl + endURL
String strURL
strURL = frontURL
strURL = body
String strDocId
strDocId = frontURL
strDocId = docid
count++
}
}
}
result = null
}
} catch (Exception e) {
e.printStackTrace()
return respList
}
return respList
}
It seems to me like
def summary = result.documents.first()
if (summary) {
String docid = summary.getSummaryField("infadocid").getStringValue()
...
strDocId = docid
}
is all you really need, because the for loop actually doesn't make much sense when all you want is to process the first record.
If there is a possibility that result.documents contains nulls, then replace first() with find()
Edit: To process more than one result:
def summaries = result.documents.take(numOfResult)
// above code assumes result.documents contains no nulls; otherwise:
// def count=0
// def summaries = result.documents.findAll { it && count++<numOfResult }
summaries.each { summary ->
String docid = summary.getSummaryField("infadocid").getStringValue()
...
strDocId = docid
}
In idiomatic Groovy code, many loops are replace by iterating methods like each()
You know the while statement also exists in Groovy ?
As a consequence, there is no reason to transform it into a for loop.
/*The below line gives me error*/
for(it in result.document && count < 1)
{
}
This line is giving you an error, because result.document will try to call result.getDocument() which doesn't exist.
Also, you should avoid using it as a variable name in Groovy, because within the scope of a closure it is the default name of the first closure parameter.
I haven't looked at the code thoroughly (or as the kids say, "tl;dr"), but I suspect if you just rename the file from .java to .groovy, it will probably work.