After issuing an DBQuery with an insert, how can I get the generated id, so I can add it back to the DAO? - jodd

Its more than just insert, really. If I already have a partially loaded DAO, how can I load the rest of it?
What I'm going to do is to do a select query, and then use BeanCopy. I'd rather have the result set mapper directly set the properties on the DAO.

Ok, let me try to answer this. For all generated values (like auto-generated IDs) you can use the following flow:
q = DbEntitySql.insert(foo).query();
// ... or any other way to get DbQuery
q.setGeneratedColumns("ID");
q.executeUpdate();
DbOomUtil.populateGeneratedKeys(dao, q);
Basically, for each query/dao you need to specify fields that are autogenerated. Currently there is no annotation for doing so - we are trying to keep number of annotations small as possible. We are working on making this more automatic.
Now, for populating the DAO. I would not use BeanCopy - simply load new DAO instance and ditch the old one. So after you execute the full select query you will get the full DAO loaded, and just continue with it.

Related

How to Insert data from datagridview Rows to mysql database in vb.net using stored procedure

Im stucked. I am trying to insert data from the grid to the database.But I'm stucked.
Slugsie's comment is pertinent, but needs to go a little further:
You're actually clearing the entire parameters collection before you call the procedure. If it were a house, you went to all the effort to build the whole thing, then at the last minute you demolish it and show the customer a cleared lot
Don't clear the Parameters collection at all. Add all the parameters to it OUTSIDE the loop, then inside the loop, set the values:
'general pattern
cmd.Parameters.AddWithValue("param1", "...")
cmd.Parameters.AddWithValue("param2", "...")
cmd.Parameters.AddWithValue("param3", "...")
cmd.Parameters.AddWithValue("param4", "...")
For Each something In somethingElse
cmd.Parameters("param1").Value = something.Whatever1
cmd.Parameters("param2").Value = something.Whatever2
cmd.Parameters("param3").Value = something.Whatever3
cmd.Parameters("param4").Value = something.Whatever4
cmd.Execute...
Next something
That's the pattern you should be adopting
Though jmc also makes a useful comment; you could make your life a lot easier by
adding a DataSet type file to your project
open it, right click the surface, choose Add TableAdapter
when configuring the wizard for the adapter, say you want to use stored procedures for your select, insert, update etc
wire the procedures up to the relevant table columns
Now in code you can save data just by a single line or two:
Dim t as New WhateverTableAdapter
t.Update(yourWhateverDatatable) 'the WhateverDataTable is bound to a grid, the user has edited the rows in it by changing the grid
That Update() call will perform any necessary use of the Insert/Update/Delete procedures depending on if the datarow in the table is an Added, Modified or Deleted state

How to use a variable as a value for a #Query in Spring

I know the title is not really explaining the problem so I will try to give more details.
I have a String in the Controller, something like this (keep in mind that this String is not manually written since it's dynamic, there are 7 filters and I want to return the information based on the filters selected, so I can't just put the String in the #Query value, since some filters will remain untouched and you cannot SELECT * WHERE value = *)
String query = "SELECT * FROM table WHERE column1=value1 AND column2=value2"
Now, the Queries are made in the Repository, but I really have no idea how to make the value of that query to be this String, something like this :
#Query(value = query, nativeQuery = true)
public List<ExampleEntity> testFunction(String query);
My first idea was to do this :
#Query(value = "?", nativeQuery = true)
public List<ExampleEntity> testFunction(String query);
But it inputs the whole String inside ' '
'SELECT * FROM table WHERE column1=value1 AND column2=value2'
(now that I think about this, it does that because the compiler sees this as like I'm trying to set the value of something to be the String, makes sense but I wish there could be a way to simply set the input of the function to be the value of the Query :/ )
Sooo ... is there any other way to use that string as the query value?
Annotations are on classes, they are set at compile time. You can’t change them at runtime. Spring can’t change them either.
What you could do is check out how to use Specifications to construct queries, or use your existing query constructing code within a custom JPA repository. Defining repositories with interfaces is a good option for simple cases, but this is not a simple case.
It would be better to move your query building code out of the controller layer and into the repository, btw. Even assuming everything in the current workflow is secure, having a repository take a native query as a parameter just isn’t a good look, it’s wide open to abuse.
I took a different approach to solve this problem that is much simpler than using Specifications.
After searching how can you send a Query in the Controller I found jdbcTemplate that is Standard in Spring (no need to add a dependency or anything else)
These are the steps that I took and in the end, everything works at it should.
1 Autowire the JdbcTemplate in the Controller
#Autowired
private JdbcTemplate jdbcTemplate;
2 Set the return to be the Query
return jdbcTemplate.queryForList(query);
Keep in mind that this is for multiple Columns, if you have to return only one column I think you have to use something like this :
return jdbcTemplate.query(query, new SingleColumnMapper(Example.class)
It might not be the safest or the most recommended way of solving this, but it worked for me.

How to implement an auto refresh on a datagridview bound to a MySQL database in Visual Basic (.NET)

I have a visual basic program with a datagridview that is bound to a mysql database upon loading... I also have fields where you can update selected rows, add, delete, etc. and I'd like to have an auto-refresh upon updating... However, I cannot figure out how to do this as the table just adds the new rows underneath the old rows. Is there a way to have a complete table refresh for the mysql bound datagridview without having to re-launch the program?
Thanks in advance!
The grid is not bound to MySQL. It's bound to a DataTable. If you want a complete refresh of the data then simply clear that table and then repopulate it.
myDataTable.Rows.Clear()
As jmcilhinney suggested, datagridviews are bound to DataTables (or sometimes lists in my own case), so what he said sounds like it should work. Since, apparently, it didn't do as you wanted, here's my suggestion:
You said you have "fields" where you can update, add, delete, etc. a selected row, correct? It also sounds like you're doing something with new rows. As you've suggested that it's a databound gridview, I doubt that you're actually adding them in the typical way but instead have some sort of programmatic alternative.
So, try implementing your solution as less of a "rewrite" and more of a SQL update. When the user enters the data for the row that they wish to update or the new row they'd wish to create, search the rows for a given primary key.
In the case of a datatable, the code would look something like this:
string s = "primaryKeyValue";
DataRow foundRow = dataSet1.Tables["AnyTable"].Rows.Find(s);
foundRow.Item["DesiredColumn"] = newValue;
source: https://msdn.microsoft.com/en-us/library/y06xa2h1.aspx
In the case of a list bound as a DataSource, I believe you'd have to do something like this:
List<Thing> things = new List<Thing>(); // in case this wasn't obvious
Thing tempThing;
tempThing = things.Find(x => x.PartName.Contains("seat")));
tempThing.Value = newValue;
After you've modified the underlying datasource, then, theoretically, you should be able to simply call DataGridView.Refresh(), but you may have to do something trickier like set the datasource to null and then rebind it in order to force EndEdit.
I know this is late, but I hope it still helps someone.

Forcing LINQ to use a Stored Procedure when accessing a Database

I've done some searches (over the web and SO) but so far have been unable to find something that directly answer this:
Is there anyway to force L2S to use a Stored Procedure when acessing a Database?
This is different from simply using SPROC's with L2S: The thing is, I'm relying on LINQ to lazy load elements by accessing then through the generated "Child Property". If I use a SPROC to retrieve the elements of one table, map then to an entity in LINQ, and then access a child property, I believe that LINQ will retrieve the register from the DB using dynamic sql, which goes against my purpose.
UPDATE:
Sorry if the text above isn't clear. What I really want is something that is like the "Default Methods" for Update, Insert and Delete, however, to Select. I want every access to be done through a SPROC, but I want to use Child Property.
Just so you don't think I'm crazy, the thing is that my DAL is build using child properties and I was accessing the database through L2S using dynamic SQL, but last week the client has told me that all database access must be done through SPROCS.
i don't believe that there is a switch or setting that out of the box and automagically would map to using t sprocs the way you are describing. But there is now reason why you couldn't alter the generated DBML file to do what you want. If I had two related tables, a Catalog table and CatalogItem tables, the Linq2SQL generator will naturally give me a property of CatalogItems on Catalog, code like:
private EntitySet<shelf_myndr_Previews_CatalogItem> _shelf_myndr_Previews_CatalogItems;
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="CatalogItem", Storage="_CatalogItems", ThisKey="Id", OtherKey="CatalogId")]
public EntitySet<CatalogItem> CatalogItems
{
get
{
return this._CatalogItems;
//replace this line with a sproc call that ultimately
//returns the expected type
}
set
{
this._CatalogItems.Assign(value);
//replace this line with a sproc call that ultimately
//does a save operation
}
}
There is nothing stopping you from changing that code to be sproc calls there. It'd be some effort for larger applications and I'd be sure that you be getting the benefit from it that you think you would.
How about loading the child entities using the partial OnLoaded() method in the parent entity? That would allow you to avoid messing with generated code. Of course it would no longer be a lazy load, but it's a simple way to do it.
For example:
public partial class Supplier
{
public List<Product> Products { get; set; }
partial void OnLoaded()
{
// GetProductsBySupplierId is the SP dragged into your dbml designer
Products = dataContext.GetProductsBySupplierId(this.Id).ToList();
}
}
Call your stored procedure this way:
Where GetProductsByCategoryName is the name of your stored procedure.
http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx

How to update in Linq to SqL?

every example I seen shows how to do a update query in linq to sql by doing this.
// grab entity you want to update
entity.UserId = "123"; // update the fields you want to update.
entity.Name = "bob";
Dbcontext.SubmitChanges();
I am wondering can you juse pass in a new object and have it figure it out?
Like could I do this?
Enity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:
// grab entity record
// shove record ito the found record
// it figured out what to update and what no to update
Depending on what exactly you want to do you either need the InsertOnSubmit method, or the Attach method of the respective table (i.e. dbContext.Entities). InsertOnSubmit is used to add a record, while Attach can be used if you want to affect an UPDATE without having to first SELECT the record (you already know the primary key value)
In the case you have the dbContext available and ready, just add InsertOnSubmit:
Entity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:
Dbcontext.InsertOnSubmit(myEntity);
Dbcontext.SubmitChanges();
As the name of the method implies, this will insert your new entity into the database on calling SubmitChanges.
Marc
If you want to do this for performance reasons then you shouldn't worry about it. Linq to Sql will cache objects locally so that just grabbing an entity by ID to modify some fields is very cheap.
It's possible to attach and persist it to the database, however you may want to set a field to check for concurrency (ie LastModified).
If you are going to use the Attach method on the data context, you need to set the primary/composite keys before you attach the entity (so you don't trigger INotifyPropertyChanging, INotifyPropertyChanged events).