In LinqToSql, if I want to access a non-related entity in an entity partial class, how do I do this without creating a new DataContext?
Here's the scenario:
I have the tables Client, IssueType and ClientIssueType. A Client may specify a list of IssueTypes if they do not want to use the default IssueTypes. I have the default IssueTypes in the ClientIssueType table with a ClientId of null.
In my Client partial I'd like to try to retrieve all IssueTypes, and if none are found, return all default IssueTypes. The only way I can see of accessing the IssueTypes with a null ClientId is by accessing the table through a new DataContext, which is problematic once I want to start assigning them to Issues.
Where am I going wrong?
I have resolved the issue by moving the logic out of the entity partial class and into the DataContext partial class. When I call the method I pass in the Client entity.
Related
I'm using Spring Boot with Hibernate. I'm trying to delete all the contents of a MySQL table when the server reloads. I know it sounds dumb, but I can't really find a way to do it, probably because it sounds dumb. Any ideas?
Since you want only a single table cleared and not all the schema you cannot use ddl-auto properties.
I suggest adding your deleteAll logic for that table to a ApplicationListener on the event ContextRefreshedEvent where you can use all spring beans (this is the difference to #PostConstructor where you can't) so you can annotate this class as spring service and use autowired in it
public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
//Do your job
}
}
or if you don't need anything specific just do your logic in a #PostConstruct block of any class, though you need all your context to be initialized in this specific case (#PostConstruct only guarantees that autowiring is finished in the annotated bean )
Here's a list of event http://www.logicbig.com/tutorials/spring-framework/spring-core/spring-events/
if you want to delete all contents of your tables ,you can do it with adding following property in your application.properties. create property will create all tables at the starting time
spring.jpa.hibernate.ddl-auto=create
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.
I have a standard update happening via linq to sql but the data does not persist to the database.
I am using an auto-generated class via the .dbml file designer.
The update statement is below:
public static void UpdateEmailsInWorkingTable(Guid emailGuid, string modifiedEmail)
{
using (EmailDBDataContext DBContext = new EmailDBDataContext())
{
EmailAddress_Update EAUpdated = (from e in DBContext.EmailAddress_Updates
where e.EmailGuid == emailGuid
select e).SingleOrDefault();
EAUpdated.EmailAddress = modifiedEmail;
EAUpdated.IsValid = 'Y';
EAUpdated.UpdateFlag = true;
EAUpdated.LastChangedDtTm = DateTime.Now;
try
{
DBContext.SubmitChanges(ConflictMode.FailOnFirstConflict);
}
catch (ChangeConflictException ex)
{
// do stuff here
}
}
}
I looked through my auto-generated DataContext class and the only glaring difference is that the table in question EmailAddress_Update does not implement the two interfaces INotifyPropertyChanging and INotifyPropertyChanged that the other auto-generated entities do.
I am assuming that this is the cause of why the changes are not being persisted is it not???
To put it simply none of the Extensibility Method Definitions get generated for any part of this one class. If this is the cause of my problems, what in the database would be causing this to not auto-generate properly??
Thanks~
I posted this question on MSDN as well here: MSDN Linq to Sql if you wanted to see the replies. But I found part of the reason why the code doesn't generate.
Here is a piece from my MSDN response:
I created a small test table without a primary key and added it to the designer and sure enough it didn't generate any of the Extensibility methods for that instance.
So I then added a primary key to the same table and re-added it to the designer and sure enough all of the extensibility methods and change tracking events were generated.
My question now is why must there be a primary key for this stuff to auto-generate?
Ok so to answer my own question "My question now is why must there be a primary key for this stuff to auto-generate?" I found it in the book Pro LINQ written by Joe Joseph C. Rattz, Jr.
I was reading how to handle views versus tables and he says this:
"Because the entity classes generated for views do not contain entity class properties that are mapped as primary keys, they are read-only. If you consider that without primary keys, the DataContext has no effective way to provide identity tracking, this makes sense."
Mystery and problem solved.
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
I am using annotations to map a basic collection of Strings to an existing entity like this. Inside the parent entity class:
#org.hibernate.annotations.CollectionOfElements
#JoinTable (name="GoalToAchieve_entry", joinColumns=#JoinColumn(name="goalToAchieve_id"))
#org.hibernate.annotations.Sort(type = org.hibernate.annotations.SortType.NATURAL)
private SortedSet<String> entries = new TreeSet<String>();
This works fine. I have a 2-column (goalToAchieve_id and element) table resulting from the join. So I was wondering, how can I add a date/time stamp (auto-generated by MySQL) to each String of the collection. So that I can display a 3rd column with a time stamp every time a new String is added to the collection? The objective is to use a collection of simple objects (Strings) and not have to create a whole new entity (with a time/date field).
Is there a recommended way to do that? I believe even if I provide a timestamp field at the jsp interface which handles the adding of new Strings to the collection, it would still be a hibernate issue, since I need the timestamp to be persisted on the db.
Thanks in advance for any help.
Kindest regards
Hibernate #CollectionOfElements can be used with more than just simple types. You can define a class which contains two fields, your String value, plus a timestamp, and annotate that class with #Embeddable. Hibernate will then persist that to the database as two separate data columns. This class doesn't represent an Entity, just a composite value-type.
The next problem is how do you generate that timestamp. You could do it in java, with the default initialised value of the field being "new Date()" (or whatever).