Hibernate insert into Database new records only - java

I am trying to write some object into the database, I wrote the following code which is working fine but the problem is that because I am using a while loop, hibernate is treating every object as a new record, which causing the database to be filled with already existed value
My question is, which annotation or technique that I can use to only write the new records (new object's value) into the database, without writing the same object again incase it was written before (Insert only if not exists)
Here is my code
public class Parser {
public static void logParser() throws IOException {
// Creating the configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// Ccreating the session factory object
SessionFactory factory = cfg.buildSessionFactory();
String fileName = "example.txt";
File logfile = new File("fileName");
Scanner scanner = new Scanner(new File(fileName), "UTF-8");
while (scanner.hasNext()) {
String s = scanner.nextLine();
if (s.startsWith("Start")) {
String[] logArray = s.split("\\|");
System.out.println(Arrays.toString(logArray));
// here is the session object
Session session = factory.openSession();
// transaction
Transaction t = session.beginTransaction();
// here is where the object is being written into the DB
NetGroup ng = new NetGroup();
ng.setNetGroup(logArray[2]);
session.persist(ng);
session.saveOrUpdate(ng);
t.commit();
session.close();
System.out.println("Successfully created an object and wrote its values into database ");
System.out.println();
}
}
scanner.close();
System.out.println("Successfully updated the Data Base");
}
}

Your issue is happened because in each loop you create a new entity and persist it, then you commit and close the session, so when begin a new transaction in second loop there is no reference between the already persisted entity and second one, so new entity will be created.
You need to re find your entity then update it if existed, else create new one and persist it.
That code will fix your issue
public class Parser {
public static void logParser() throws IOException {
// Creating the configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// Ccreating the session factory object
SessionFactory factory = cfg.buildSessionFactory();
String logFileName = "example.txt";
File logfile = new File("fileName");
Scanner scanner = new Scanner(new File(fileName), "UTF-8");
// here is the session object
Session session = factory.openSession();
// transaction
Transaction t = session.beginTransaction();
while (scanner.hasNext()) {
String s = scanner.nextLine();
if (s.startsWith("Start")) {
String[] logArray = s.split("\\|");
System.out.println(Arrays.toString(logArray));
Query query = session.createQuery("FROM " + getTableName() + " Where your condition "); // use unique filed
List<NetGroup> list = query.list();
if(list.size()==0){
NetGroup ng =new NetGroup();
}else{
ng =list.get(0);
}
ng.setNetGroup(logArray[2]);
session.saveOrUpdate(ng);
System.out.println("Successfully created an object and wrote its values into database ");
System.out.println();
}
}
session.close();
t.commit();
scanner.close();
System.out.println("Successfully updated the Data Base");
}
}
Make sure put valid condition instead of "your condition"

I think you can use the primary key concept there to remove the duplicacy of rows and use the saveOrUpdate method.
If we work with hibernate API there should be one PK in the class.
session.saveOrUpdate(ng);
That above method check the record on the basis of primary key, if PK does not exists in the DB then it fire the insert query if exists then it update the same record rather than inserting new one.
public class NetGroup
{
private int primaryKeyId;
public int getprimaryKeyId() {
return primaryKeyId;
}
public void setprimaryKeyId(int primaryKeyId) {
this.primaryKeyId = primaryKeyId;
}
}

Related

The input authorization token can't serve the request.(azure-documentdb-java)

When creating a program to connect to cosmos db using Java, an error occurred and I asked a question.
When I executed the source code at the following URL,
The following error related to authentication occurred.
error message
Exception in thread "main" com.microsoft.azure.documentdb.DocumentClientException:
The input authorization token can't serve the request.
Please check that the expected payload is built as per the protocol, and check the key being used.
Server used the following payload to sign:
source
https://github.com/Azure/azure-documentdb-java#eclipse
import java.io.IOException;
import java.util.List;
import com.google.gson.Gson;
import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.Document;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.DocumentCollection;
import com.microsoft.azure.documentdb.RequestOptions;
public class HelloWorld {
// Replace with your DocumentDB end point and master key.
private static final String END_POINT = "[YOUR_ENDPOINT_HERE]";
private static final String MASTER_KEY = "[YOUR_KEY_HERE]";
// Define an id for your database and collection
private static final String DATABASE_ID = "TestDB";
private static final String COLLECTION_ID = "TestCollection";
// We'll use Gson for POJO <=> JSON serialization for this sample.
// Codehaus' Jackson is another great POJO <=> JSON serializer.
private static Gson gson = new Gson();
public static void main(String[] args) throws DocumentClientException,
IOException {
// Instantiate a DocumentClient w/ your DocumentDB Endpoint and AuthKey.
DocumentClient documentClient = new DocumentClient(END_POINT,
MASTER_KEY, ConnectionPolicy.GetDefault(),
ConsistencyLevel.Session);
// Start from a clean state (delete database in case it already exists).
try {
documentClient.deleteDatabase("dbs/" + DATABASE_ID, null);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
// Define a new database using the id above.
Database myDatabase = new Database();
myDatabase.setId(DATABASE_ID);
// Create a new database.
myDatabase = documentClient.createDatabase(myDatabase, null)
.getResource();
System.out.println("Created a new database:");
System.out.println(myDatabase.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Define a new collection using the id above.
DocumentCollection myCollection = new DocumentCollection();
myCollection.setId(COLLECTION_ID);
// Set the provisioned throughput for this collection to be 1000 RUs.
RequestOptions requestOptions = new RequestOptions();
requestOptions.setOfferThroughput(1000);
// Create a new collection.
myCollection = documentClient.createCollection(
"dbs/" + DATABASE_ID, myCollection, requestOptions)
.getResource();
System.out.println("Created a new collection:");
System.out.println(myCollection.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Create an object, serialize it into JSON, and wrap it into a
// document.
SomePojo allenPojo = new SomePojo("123", "Allen Brewer", "allen [at] contoso.com");
String allenJson = gson.toJson(allenPojo);
Document allenDocument = new Document(allenJson);
// Create the 1st document.
allenDocument = documentClient.createDocument(
"dbs/" + DATABASE_ID + "/colls/" + COLLECTION_ID, allenDocument, null, false)
.getResource();
System.out.println("Created 1st document:");
System.out.println(allenDocument.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Create another object, serialize it into JSON, and wrap it into a
// document.
SomePojo lisaPojo = new SomePojo("456", "Lisa Andrews",
"lisa [at] contoso.com");
String somePojoJson = gson.toJson(lisaPojo);
Document lisaDocument = new Document(somePojoJson);
// Create the 2nd document.
lisaDocument = documentClient.createDocument(
"dbs/" + DATABASE_ID + "/colls/" + COLLECTION_ID, lisaDocument, null, false)
.getResource();
System.out.println("Created 2nd document:");
System.out.println(lisaDocument.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Query documents
List<Document> results = documentClient
.queryDocuments(
"dbs/" + DATABASE_ID + "/colls/" + COLLECTION_ID,
"SELECT * FROM myCollection WHERE myCollection.email = 'allen [at] contoso.com'",
null).getQueryIterable().toList();
System.out.println("Query document where e-mail address = 'allen [at] contoso.com':");
System.out.println(results.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Replace Document Allen with Percy
allenPojo = gson.fromJson(results.get(0).toString(), SomePojo.class);
allenPojo.setName("Percy Bowman");
allenPojo.setEmail("Percy Bowman [at] contoso.com");
allenDocument = documentClient.replaceDocument(
allenDocument.getSelfLink(),
new Document(gson.toJson(allenPojo)), null)
.getResource();
System.out.println("Replaced Allen's document with Percy's contact information");
System.out.println(allenDocument.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Delete Percy's Document
documentClient.deleteDocument(allenDocument.getSelfLink(), null);
System.out.println("Deleted Percy's document");
System.out.println("Press any key to continue..");
System.in.read();
// Delete Database
documentClient.deleteDatabase("dbs/" + DATABASE_ID, null);
System.out.println("Deleted database");
System.out.println("Press any key to continue..");
System.in.read();
}
}
enviroment
java : openjdk 11
I would be grateful if you could give us any suggestions.
The error was due to the old version being built.
When built with the latest version 2.4.6, it works properly.
https://mvnrepository.com/artifact/com.microsoft.azure/azure-documentdb/2.4.6

How to call 2 different method inside a method

i have cleanse method which is cleaning data while i am giving input from eclipse console, while entering i have putted some field as null, i am storing the cleanse data in map and calling that data in 2 different method for searching but it is calling everytime one method only
public void cleanse(SiperianClient oSiperianClient) {
Scanner sc = new Scanner(System.in);
Field accountfield = new Field();
accountfield.setName("Acct_Name");
writeStringLog("Enter Account Name:");
accountfield.setValue(sc.nextLine()); // "Arthritis Group"
record.setField(accountfield);
/// ...so on ..
Map<String, Object> cleanseMap = new HashMap<>();
while (iterator.hasNext()) {
Record rec = iterator.next();
// Collection<Field> fields = rec.getFields();
cleanseMap.put("CUST_NM", rec.getField("CUST_NM").getValue());
cleanseMap.put("ADDR_LN1", rec.getField("ADDR_LN1").getValue());
cleanseMap.put("ADDR_LN2", rec.getField("NPI_ID").getValue());
}
if (cleanseMap.get("NPI_ID").equals(NPI_ID)) {
this.SearchMatch(cleanseMap, oSiperianClient);
} else {
this.searchQueryMatch(oSiperianClient);
}
}
here NPI ID is null as i have not inserted any value from console

How To Populate Jtable Using rs2xml jar library

Dear friends i would like to know how to display the result set to jtable using rs2xml i know jtablename.setmodel(dbutils.setresultsettotable(rs)); but i would like to know that how to retriev all records and show them in jtablle my code is
private void search_by_topic() throws SQLException, ClassNotFoundException {
try
{
SessionFactory sf;
Configuration cfg=new Configuration();
System.out.println("search_by_topic me agaya");
cfg.configure("hiber_config/hibernate.cfg.xml");
sf=cfg.buildSessionFactory();
Session ses=sf.openSession();
ses.beginTransaction();
Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
qr1.setParameter("chapter_id", chap_id);
List<Topic> topic_list=qr1.list();
top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
System.out.println("Topic ID is "+top_id);
Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
qr2.setParameter("import_level", topicimport);
qr2.setInteger("import_level_id",top_id);
List<Test> test_list=qr2.list();
//Field[] fields = null;
System.out.println("Size of test_list is"+test_list.size());
//Iterator<Test> itr=test_list.iterator();
int[] test_id=new int[test_list.size()];
for(int j=0;j<test_list.size();j++)
{
System.out.println("Test_List Import Wale me agaya");
//fields=t.getClass().getDeclaredFields();
test_id[j]=test_list.get(j).getId();
System.out.println("test_id: is "+test_id[j]);
}
System.out.println("Size of test_id array is "+test_id.length);
for(int j=0;j<test_id.length;j++)
{
System.out.println("test_id now is "+j);
int studentid=98;
String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
Statement pst=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=pst.executeQuery(sqlquery);
System.out.println(rs.getRow());
System.out.println(rs.toString());
jTable1.revalidate();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
//jTable1.revalidate();
/*SessionFactory sf1;
Configuration cfg1=new Configuration();
System.out.println("join query me agaya");
cfg1.configure("hiber_config/hibernate.cfg.xml");
sf1=cfg.buildSessionFactory();
Session ses1=sf1.openSession();
ses1.beginTransaction();
ses1.doWork(new Work()
{
#Override
public void execute(java.sql.Connection cnctn) throws SQLException
{
java.sql.PreparedStatement pst=cnctn.prepareStatement(sqlquery);
rs=pst.executeQuery();
System.out.println(rs.toString());
}
});
ses1.getTransaction().commit();
}
ses.getTransaction().commit();
System.out.println("Test Data Retrieved");
ses.close();*/
}
}
catch(HibernateException e)
{
e.printStackTrace();
}
}
}
my code is working here correctly and i am able to retrieve all the resultset but in jtable i am only getting the last loop record not every loop record
Please help me
private void search_by_topic() throws SQLException, ClassNotFoundException {
try
{
SessionFactory sf;
Configuration cfg=new Configuration();
System.out.println("search_by_topic me agaya");
cfg.configure("hiber_config/hibernate.cfg.xml");
sf=cfg.buildSessionFactory();
Session ses=sf.openSession();
ses.beginTransaction();
Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
qr1.setParameter("chapter_id", chap_id);
List<Topic> topic_list=qr1.list();
top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
System.out.println("Topic ID is "+top_id);
Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
qr2.setParameter("import_level", topicimport);
qr2.setInteger("import_level_id",top_id);
List<Test> test_list=qr2.list();
//Field[] fields = null;
System.out.println("Size of test_list is"+test_list.size());
//Iterator<Test> itr=test_list.iterator();
int[] test_id=new int[test_list.size()];
for(int j=0;j<test_list.size();j++)
{
System.out.println("Test_List Import Wale me agaya");
//fields=t.getClass().getDeclaredFields();
test_id[j]=test_list.get(j).getId();
System.out.println("test_id: is "+test_id[j]);
}
System.out.println("Size of test_id array is "+test_id.length);
for(int j=0;j<test_id.length;j++)
{
System.out.println("test_id now is "+j);
int studentid=98;
String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
Statement pst=con.createStatement();
rs=pst.executeQuery(sqlquery);
while(rs.next())
{
//JOptionPane.showMessageDialog(null, "Table me Agaaya");
System.out.println("Number of rows:- "+rs.getRow());
System.out.println(rs.toString());
}
}
ses.getTransaction().commit();
System.out.println("Test Data Retrieved");
ses.close();
}
catch(HibernateException e)
{
e.printStackTrace();
}
}
}
this is my code and its working fine in system.out.println it showing all data now can u tell me how to pass this data in jtable and to let you know when i use dbutils its also retrieve column name automatically and i am not giving the column name in jtable manually
i know jtablename.setmodel(dbutils.setresultsettotable(rs));
Well DBUtils creates a single TableModel
but in jtable i am only getting the last loop record not every loop record
You keep replacing the old TableModel with a new TableModel.
So you have two choices:
You need to create multiple tables, one for each TableModel and add each JTable to the frame
You need to copy the data from each TableModel into a master TableModel and then display the master TableModel into in single JTable. So this means that outside of the loop your create a DefaultTableModel with just the column names and 0 rows of data. Then instead each loop your then copy each row of data from the DBUtils model to your main TableModel. Then outside the loop your create the table using the main TableModel.
Edit:
The basic structure of the code would be something like:
// Create an empty table model
String[] columnNames = {"Column1", "Column2", ...};
DefaultTableModel groupModel = new DefaultTableModel(columnNames,0);
...
// loop for all the ids
for(int j=0;j<test_id.length;j++)
{
...
// copy the data from the idc table model to the group table model
DefaultTableModel idModel = DbUtils.resultSetToTableModel(rs);
for (int i = 0; I < idModel.getRowCount())
{
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < rsModel.getColumnCount()
row.addElement( rsModel.getValueAt(i, j);
groupModel.addRow( row );
}
}
JTable table = new JTable( groupModel );

CommandTable Cystal Report Error

I have a Crystal Report that was written using a complex SQL and I'm trying to invoke that using the Crystal Report Java API. This report has a Command object associated with it.
I load the report and set the connection parameters.
Then I try to set the Connection information to the current JDBC Profile. Meaning Test Environment credentials.
I get an exception. I tried with Version 11. Version 12 both. None of them seems to be working.
I'm getting the exception when I invoke the following piece of code. This piece of code works just fine with reports without "Command" sqls.
try{
clientDoc.getDatabaseController().setTableLocation(
origTable, newTable);
}catch(Exception ex){
ex.printStackTrace();
}
See below for the entire code. Please reply if anyone knows how to work around this.
private static void changeDataSource(ReportClientDocument clientDoc,
String reportName, String tableName, String username,
String password, String connectionURL, String driverName,
String jndiName) throws ReportSDKException {
PropertyBag propertyBag = null;
IConnectionInfo connectionInfo = null;
ITable origTable = null;
ITable newTable = null;
// Declare variables to hold ConnectionInfo values.
// Below is the list of values required to switch to use a JDBC/JNDI
// connection
String TRUSTED_CONNECTION = "false";
String SERVER_TYPE = "JDBC (JNDI)";
String USE_JDBC = "true";
String DATABASE_DLL = "crdb_jdbc.dll";
String JNDI_OPTIONAL_NAME = jndiName;
String CONNECTION_URL = connectionURL;
String DATABASE_CLASS_NAME = driverName;
// Declare variables to hold database User Name and Password values
String DB_USER_NAME = username;
String DB_PASSWORD = password;
System.out.println("Trusted_Connection:" + TRUSTED_CONNECTION);
System.out.println("Server Type:" + SERVER_TYPE);
System.out.println("Use JDBC:" + USE_JDBC);
System.out.println("Database DLL:" + DATABASE_DLL);
System.out.println("JNDIOptionalName:" + JNDI_OPTIONAL_NAME);
System.out.println("Connection URL:" + CONNECTION_URL);
System.out.println("Database Class Name:" + DATABASE_CLASS_NAME);
System.out.println("DB_USER_NAME:" + DB_USER_NAME);
System.out.println("DB_PASSWORD:" + DB_PASSWORD);
// Obtain collection of tables from this database controller
if (reportName == null || reportName.equals("")) {
Tables tables = clientDoc.getDatabaseController().getDatabase()
.getTables();
for (int i = 0; i < tables.size(); i++) {
origTable = tables.getTable(i);
if (tableName == null || origTable.getName().equals(tableName)) {
newTable = (ITable) origTable;
newTable.setQualifiedName(origTable.getAlias());
connectionInfo = newTable.getConnectionInfo();
// Set new table connection property attributes
propertyBag = new PropertyBag();
// Overwrite any existing properties with updated values
propertyBag.put("Trusted_Connection", TRUSTED_CONNECTION);
propertyBag.put("Server Type", SERVER_TYPE);
propertyBag.put("Use JDBC", USE_JDBC);
propertyBag.put("Database DLL", DATABASE_DLL);
propertyBag.put("JNDIOptionalName", JNDI_OPTIONAL_NAME);
propertyBag.put("Connection URL", CONNECTION_URL);
propertyBag.put("Database Class Name", DATABASE_CLASS_NAME);
connectionInfo.setAttributes(propertyBag);
connectionInfo.setUserName(DB_USER_NAME);
connectionInfo.setPassword(DB_PASSWORD);
// Update the table information
try{
clientDoc.getDatabaseController().setTableLocation(
origTable, newTable);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
// Next loop through all the subreports and pass in the same
// information. You may consider
// creating a separate method which accepts
if (reportName == null || !(reportName.equals(""))) {
IStrings subNames = clientDoc.getSubreportController()
.getSubreportNames();
for (int subNum = 0; subNum < subNames.size(); subNum++) {
Tables tables = clientDoc.getSubreportController()
.getSubreport(subNames.getString(subNum))
.getDatabaseController().getDatabase().getTables();
for (int i = 0; i < tables.size(); i++) {
origTable = tables.getTable(i);
if (tableName == null
|| origTable.getName().equals(tableName)) {
newTable = (ITable) origTable;
newTable.setQualifiedName(origTable.getAlias());
// Change connection information properties
connectionInfo = newTable.getConnectionInfo();
// Set new table connection property attributes
propertyBag = new PropertyBag();
// Overwrite any existing properties with updated values
propertyBag.put("Trusted_Connection",
TRUSTED_CONNECTION);
propertyBag.put("Server Type", SERVER_TYPE);
propertyBag.put("Use JDBC", USE_JDBC);
propertyBag.put("Database DLL", DATABASE_DLL);
propertyBag.put("JNDIOptionalName", JNDI_OPTIONAL_NAME);
propertyBag.put("Connection URL", CONNECTION_URL);
propertyBag.put("Database Class Name",
DATABASE_CLASS_NAME);
connectionInfo.setAttributes(propertyBag);
connectionInfo.setUserName(DB_USER_NAME);
connectionInfo.setPassword(DB_PASSWORD);
// Update the table information
clientDoc.getSubreportController()
.getSubreport(subNames.getString(subNum))
.getDatabaseController()
.setTableLocation(origTable, newTable);
}
}
}
}
}
Add after this line of yours
connectionInfo.setPassword(DB_PASSWORD);
newTable.setConnectionInfo(connectionInfo);
//This will add connection parameters to the new table
Instead of
clientDoc.getDatabaseController().setTableLocation(origTable, newTable);
replace this with
clientDoc.getDatabaseController ().setTableLocation (newTable, tables.getTable(i));

Issue in updating records in Hibernate

Hi I am using Hibernate to update the records in a table. And I'm inserting same records in another table. It is in a loop, but I am getting exception as lock wait timeout exception when I am updating records. Please could anybody resolve this problem? Thanks in advance!
try {
SalesInventoryDAO dao = new SalesInventoryDAO();
sess = HibernateUtil.getSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
GoodsRecievedForm item = (GoodsRecievedForm) form;
GoodsRecieved bk = new GoodsRecieved();
bk.setGoodsId(item.getGoodsId());
InventoryOrder order = (InventoryOrder) sess.get(InventoryOrder.class, item.getOrderNo());
bk.setOrderNo(order);
// if (order.getQuotation().getQuotationNo() != null) {
// bk.setQuotation(order.getQuotation().getQuotationNo());
// } else {
// bk.setQuotation(null);
// }
java.util.Date temp = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(item.getRecievedDate());
java.sql.Date temp1 = new java.sql.Date(temp.getTime());
bk.setRecievedDate(temp1);
bk.setOrderQty(order.getTotalqty());
bk.setReceivedPersonName(item.getReceivedPersonName());
bk.setReceivedQty(item.getReceivedQty());
bk.setConditionOfMaterial(item.getConditionOfMaterial());
UserEntity msg;
HttpSession session = request.getSession(false);
msg = (UserEntity) session.getAttribute("user");
bk.setAddedBy(msg);
bk.setAddedDate(new Date());
int[] item1111 = item.getGoodsDetails();
String[] productre = item.getGoodsDetailsName();
float proqty[] = item.getGoodsDetailsQty();
float price[] = item.getGoodsDetailsPrice();
float receivedqty[] = item.getReceivedquantity();
GoodsReceivedDetails mb;
Set<GoodsReceivedDetails> purDetails = new HashSet();
for (int i = 0; i < productre.length; i++) {
mb = new GoodsReceivedDetails();
mb.setGoodsDetailsName(productre[i]);
mb.setGoodsDetailsQty(proqty[i]);
mb.setGoodsDetailsPrice(price[i]);
mb.setReceivedquantity(receivedqty[i]);
//System.out.println("productre" + productre[i]);
int id3 = item1111[i];
//System.out.println("id3id3id3id3" + id3);
// int id3 = Integer.parseInt(productre[i]);
Item idf = (Item) sess.get(Item.class, id3);
float qty = (idf.getItemStock() + mb.getReceivedquantity());
// mb.setItemId(idf);
// mb.setItemId(idf);
dao.updateitem(qty, idf);
//dao.updateitem(idf);
mb.setGoodsId(bk);
sess.save(mb);
purDetails.add(mb);
}
bk.setGoodsDetails(purDetails);
sess.save(bk);
tx.commit;
//System.out.println("comming");
// List ls = gdao.getOrderItems(order.getOrderId());
// for (Iterator it = ls.iterator(); it.hasNext();) {
// InventoryOrderDetails inv = (InventoryOrderDetails) it.next();
// gdao.updateitem(inv.getItemId().getItemStock() + bk.getReceivedQty(), inv.getItemId());
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
sess.close();
}
This is my dao code..
public void updateitem(float stock, Item itm) {
Session ses = HibernateUtil.getSessionFactory().openSession();
////System.out.println("itmitmitm" + itm.getItemId());
Transaction tx = ses.beginTransaction();
Query qry = ses.createQuery("UPDATE Item set itemStock='" + stock + "' where itemId='" + itm.getItemId() + "'");
qry.executeUpdate();
ses.close();
tx.commit();
}
You have initialized a the transaction by sess.beginTransaction(); in the beginning and before even committing the transaction, you've trying to re-initialize the transaction. This will lead to memory leaks as the previous transactions hasn't been committed. So, before you begin another transaction, commit the previous one.
And here are some suggestions:
‘Lock wait timeout’ occurs typically when a transaction is waiting on
row(s) of data to update which is already been locked by some other
transaction.
Most of the times, the problem lies on the database
side. The possible causes may be a inappropriate table design, large
amount of data, constraints etc.
Please check out this for more details.
Commit transaction before opening new one
Transaction currentTx = sess.beginTransaction();
..
currentTx.commit();
..
currentTx = sess.beginTransaction();
EDIT:
In dao you opening new transaction instead of use previous one.. you should read some tutorials about transaction management in java/hibernate.

Categories