JDBC update of different fields - mysql

I'm developing Web Service that has access to database via JDBC. I'm using DAO pattern. I've implemented all necessary methods: findAll, add, update, delete. But I got confused with update method. It has Object as input parameter. But how does he know which field needs to be updated. For example, I need to update field 'name' I use query 'update table set name='smth where id=2' but if I need to update 'surname'?? what is the best practice to tell update method what actually to update?
thank you

You'll need to change your method signature to include a Map of column names and values.
public interface FooDao<K, V> {
// other methods here, of course.
public void update(V target, Map<String, Object> parameters);
}
Have a look at the Spring JDBC template for a nice example of how to design and implement such a thing.

Related

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

LINQ to SQL -- Same User Object, different data context

I have a user object called UserSystem, which is created by a static factory class that returns User Systems. Because the factory class only exists to create this object once, then disposes, is it possible to associate my persisted UserSystem object with another instance of my database context that I create at a later point?
I would like to avoid having to query my new DatabaseContext to find the matching UserSystem object and simply associate the persisted user object from the first DatabaseContext class with my new DatabaseContext.
Thanks!
George
You probably want to Attach your object to the DataContext. There are many articles about this, for example this one. Be careful though - this method is not intended to allow you to attach objects that are already attached to another DataContext, it is only for deserialized objects that are completely unattached, which I assume is what you have.
You may use the Attach method on the Table<T> object to insert a detached data object into it. You may insert it in a modified state, or in an unmodified state. If you insert it in a modified state, the next SubmitChanges() call will include it.
The Table(Of TEntity) Attach method overloads

Linq to SQL Extensibility Method Definitions

If I have a Linq table of say User and I then do something like this;
public partial class DataAccessDataContext
{
partial void UpdateUser(User instance)
{
//do something here
}
}
What ends up happening is that the record is never updated in the database.
As soon as I get rid of the UpdateUser method the database is again updated.
I found something on the web that mentions that as soon as you implement any of the three extensibility methods of Insert, Update and Delete, then the database is no longer updated.
Is this correct and is there a way I can get this to work?
You need to call the Dynamic update method like;
this.ExecuteDynamicUpdate(instance);

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).

inserting extra data in linq to sql partial class

I have a L2S generated class called Accounts, I have a L2S class called UsersInAccounts I need to add a function call AddUserToAccount(accountid, userid) should/could this function be added to the partial Accounts class I have created or are partial classes used for getting data rather than editing data
public partial class Account
{
public void addUser(Guid userid)
{
// code
}
}
I don't think that what you are doing is a problem. In your code, you'd probably have an Account instance that you want to do things with so being able to do this:
Account theAccountIWant = GetTheAccount();
theAccountIWant.addUser(myUsersGUID);
...seems pretty intuitive. It might be an idea to do some error trapping inside your addUser method and pass back some sort of success status but that's another discussion.
edit: As advised, if you then retrieve a User object and want to attach it to the Account using the AccountUsers property then this is no use unless you pass the DataContext in.