I am inserting record in database(MySQL) based on user input. Immediate the data is inserted i want to retrieve the record i just inserted and display it in textfield.
But to my surprise nothing is retrieved. Is there some kind of way that will refresh my database immediately i insert data in db. I am using java!
public class Member {
public Member(){
final String nameMember = inputName.getText();
//Button listener action
newAccount.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try {
//this method insert data into db
subscribe();
//this retrieves the data inserted by subscribe()
createdAccountDetails(nameMember);
} catch (SQLException ex) {
Logger.getLogger(Member.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
You have to commit the data into db then only you can fetch it into results. But, it would be a bad practice to use insert and select as two different calls.
Either you can save the values in session and show them(if no exception occurred during insertion) or you can use a pl/sql function or procedure for the same.
Related
I am trying to persist to multiple entities. Sample code below:
public List<String> save(SalesInvoice salesInvoice, List<ClosingStock> closingStockList, Company company,
Receipt receipt) {
log.info("Saving Sales Invoice...");
if (salesInvoice.getSalesChallanId() == null) {
for (ClosingStock closingStock : closingStockList) {
if (existingClosingStock(closingStock.getProduct().getId().toString()) == null) {
em.persist(closingStock);
} else {
}
}
}
em.persist(salesInvoice);
receipt.setSalesInvoiceId(salesInvoice.getId());
em.persist(receipt);
return null;
}
// Edit: Add existingClosingStock method provided in comments
public ClosingStock existingClosingStock(String productId) {
try {
return (ClosingStock) em.createQuery("SELECT cv FROM ClosingStock cv WHERE cv.product.id=:productId") .setParameter("productId", productId).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
Well, when I execute this query, the data didn't persist in database, but it shows the list of newly inserted data for small times, but data didn't save in database. I got no errors in console. Also put em.getTransaction().commit(); before return does not work. When I tried persisting on single entity and put em.getTransaction().commit();, it worked perfectly. Like this:
public void save(Location location) {
log.info("Saving Location.");
em.persist(location);
em.getTransaction().commit();
}
What did I miss here?
As explained in this article, persist just schedules an entity state transition. The insert is executed during flush. If you don't commit the transaction, the flush will not be triggered automatically.
Anyway, you should always start a transaction, even if you plan to read data.
I have 2 classes
User
StockProduct
StockProduct has a relation column sold_by for User.
I am trying to retrieve sold_by for the corresponding StockProduct but, it's returning 0 objects for the following code.
/**
* GET SELLER FOR CURRENT PRODUCT
* current_stock_object: ParseObject for StockProduct
*/
ParseRelation getSellerRelation = current_stock_object.getRelation("sold_by");
ParseQuery getSeller = getSellerRelation.getQuery();
getSeller.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
if (e!=null){
e.printStackTrace();
}
Log.d("SIZE", Integer.toString(users.size()));
}
});
Output:
I successfully retrieve the relation via Parse DataBrowser.
SIDE NOTE
/**
* GET PRICE FOR CURRENT PRODUCT
*/
ParseRelation<ParseObject> getPriceRelation = current_stock_object.getRelation("prices");
ParseQuery getPrice = getPriceRelation.getQuery();
getPrice.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject>prices, ParseException e) {
Log.d("PRICE SIZE", Integer.toString(prices.size()));
System.out.println(prices.get(0).get("costPrice"));
}
});
Works perfectly fine, leaving me with the thought that, getting ParseUser requires a different approach.
Any help would be appreciated.
I would try:
ParseRelation<ParseUser> getSellerRelation = current_stock_object.getRelation("sold_by");
getSellerRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
if (e!=null){
e.printStackTrace();
}
Log.d("SIZE", Integer.toString(users.size()));
}
});
All I added was an explicit type to the ParseRelation (in this case ParseUser). The documentation uses exactly this syntax, so I'm not sure why this wouldn't work for fetching the Relation.. maybe your "current_stock_object" needs to be fetched, or the "current_stock_object" is not the one you are looking at in the Parse console. Use the debugger and check the fields of your "current_stock_object" and ensure the objectId matches the one you are looking at in the console. Again, the object could be stale may need a fetch
Side note: (unrelated possibly)
Be sure to only use ParseRelation for a many-to-many relationship, otherwise just store the ParseObjects directly as a field. In this case, you have a StockProduct with a relation to _User table. If it makes sense in your application that a StockProduct can have multiple sellers, stick with the ParseRelation. If it was actually intended that a StockProduct may only have one unique seller, switch to not using a ParseRelation
I have been making a simple program to save an employee details in mysql using hibernate framework as follows...
public class Manifest {
Session session;
public static void main(String[] args) {
Employee employee = new Employee("varun");
new Manifest().addEmployee(employee);
}
/* Method to CREATE an employee in the database */
public void addEmployee(Employee employee){
Integer employeeID=null;
SessionGenerator sessionGenerator = new SessionGenerator();
try{
session = sessionGenerator.getSessionToDb();
employeeID = (Integer) session.save(employee);
System.out.println(employeeId);
}catch (HibernateException e) {
e.printStackTrace();
}finally {
session.close();
}
}
}
I am aware of the fact that I should use session.beginTransaction(); & tx.commit() but my question is that why no exception is thrown here in my case and it is printing employeeId on console but not making any entry in database.. What the reason behind that???
1) Session.save() may perform an INSERT outside transaction boundaries: save() method returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator), this INSERT happens immediately (in order to get an identity), no matter if you are inside or outside of a transaction.
2) Commit might happen even without transaction if you set:
<property name="connection.autocommit">true</property>
that's why an exception is not raised
Check this article (Working nontransactionally with Hibernate): https://developer.jboss.org/wiki/Non-transactionalDataAccessAndTheAuto-commitMode
I use Dbutils to call elements in one table of database
private void showEvent(){
try {
String query="SELECT EventID, MemberID,Description, Date,
Time, Venue, EventTypes FROM formal UNION SELECT EventID,
MemberID,Description, Date, Time, Venue, EventTypes FROM social";
ps = c.prepareStatement(query);
rs=ps.executeQuery();
tbShowEvent.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(ShowEvent.class.getName()).log(Level.SEVERE, null, ex);
}
}
How to delete one element in table when I click the mouse to that element
Illustration: http://i.stack.imgur.com/ib77V.png
add an event listener on your delete button
create your stored procedure code for the delete in the event listener.
after a succesful delete in the DB delete the row in your table in the table Model
refresh you table. Call fireTableDataChanged() on your tableModel
I have two table and want both table must update and save altogether otherwise rollback. i am using Transaction but not getting expected result when found runtime exception. Table_1 got updated and table_2 was not updated after getting some conversion issues in my java code.
Service Class
public void startTransaction(){
try{
transaction.begin();
//Calls manager's class method to update and save the data into table
transaction.commit();
}catch(Exceptio e){
transaction.rollback();
}
}
Manager class
public void updateAndSave(){
try{
-> calls DAO method for table_1
->Update Table_1 via DAO update method
-> calls DAO method for table_2
->Update Table_2 via DAO update method
}catch(Exception e){
......
}
}