Clear MySQL table data when Spring Boot loads - mysql

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

Related

JDBC update of different fields

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.

Accessing non-related entities in LinqToSql entity classes

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.

Is it possible to impl database 'trigger' in java code? (hibernate + jpa + spring + mysql)

I am using mysql 5.5 DB, hibernate.4.0 as jpa provider to spring 3.0.5.
I have a user table and privilege table in my DB. Also I have some triggers in my DB. Those trigger implements some of our application's business logic.
For example, user john insert a record into table table_foo via my web application.
The trigger BeforeInsertTableFoo will check the user's privilege. If user doesn't have the privilege, trigger will abort this operation.
Also, if the operation is permitted, another trigger AfterInsertTableFoo will update some records in Table table_bar.
Is there any way that I can implement this logic as 'trigger' in java code? It seems like Jpa Event Listener and Hibernate Event can only do something like trigger but only in one table.
Surely I can use a java class to do the same thing. But I can't make sure that all the other developer, even myself, will use the correct java class to do db insertion or update, when the amount of business rules increased.
Thx in advance.
andrew
Check the JPA's listener more carefully. You can make one listener for many entities / tables.
Just set a listener class like this:
public class MyListener {
#PrePersist void onPrePersist(Object entity ) {}
#PostPersist void onPostPersist(Object entity) {}
#PostLoad void onPostLoad(Object entity) {}
#PreUpdate void onPreUpdate(Object entity) {}
#PostUpdate void onPostUpdate(Object entity) {}
#PreRemove void onPreRemove(Object entity) {}
#PostRemove void onPostRemove(Object entity) {}
}
And then, for all the entities for which you want a call back or "trigger" ...
#Entity #EntityListeners(MyListener.class)
public class Customer {
}
I hope this helps.
-Alex
I found some links on google, which talks about Spring managed event listeners with JPA

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 table naming

I am using VS2010 and C#
When I map/select my database tables with LINQ to SQL I have to option to change the "member" propery, but when i delete the table (because I changed something in the schema for example) and add it again the member value gets "reset". Is it possible to set/override this member programmaticly, so that I dont have to change it by hand everytime
I mean the member option of
'<'Table Name="dbo.table1" Member="table1">
All L2S ORM classes are partial, so you should be able to encapsulate the table in another property by extending the DataContext class e.g.
public partial class MyDataContext
{
public IEnumerable<Entity> Table
{
get { return DatabaseTable; }
}
}
So in the above scenario you would make your DatabaseTable private and expose it through a another property. You may still need to change that particular piece of code manually if you change the name of your table, but it means you are only changing it once and don't have to change it everytime you reference the table somewhere in your code.