mySQL Auto increment using JDBC - mysql

I have created a page and want to store it in mySQl but i want to implement autoincrement from my java program and pass it as a parameter.how to get that.I used static count=0 counter as passing but it is not happening.
This is the function i am using
static int=count++;
CorruptionStory corruptionStory =
new CorruptionStory(count, new State(stateId,stateNameSelected),
age, new Department(deptId,departmentNameSelected),
positionOfOfficial,bribeAmount, description, sqlDate);
isSuccessfullySaved = CorruptionStoryJdbcImpl.
saveCorruptionStory(corruptionStory);

I don't think it's a good idea to have the java code manage the auto incrementing of the number, you should really configure your table schema to do it for you. Here is why:
if you restart your application, you will need to write code to figure out what number to resume with.
if you have multiple instances of your program running, they will somehow need to coordinate with each other so they don't use the same number.
MySQL column definitions allow you to specify auto-increment, see this:
http://dev.mysql.com/doc/refman/5.6/en/example-auto-increment.html
it would be much better if you wrote a SQL schema file to solve this problem. Then, when you do the insert statement from the java program, you can omit that column, and MySQL will automatically set it to the next appropriate value.
Also, if you are willing to spend time studying hibernate, you can use that. Hibernate is able to generate your SQL schema automatically for you, and even update the database for you at startup. It has an annotation that lets you tell hibernate that a certain class field (table column) should be an automatically incrementing id.
I should warn you though, hibernate is not something you're going to learn overnight.

Related

Is the a way for SQLDelight to allow unrecognized expression?

I use SQLDelight's MySQL dialect on my server. Recently I plan to migrate a table to combine many fields into a JSON field so the server code no longer needs to know the complex data structure. As part of the migration, I need to do something like this during runtime - when the sever sees a client with the new version, it knows the client won't access the old table anymore, so it's safe to migrate the record to new table.
INSERT OR IGNORE INTO new_table SELECT id, a, b, JSON_OBJECT('c', c, 'd', JSON_OBJECT(…)) FROM old_table WHERE id = ?;
The only problem is - Unlike the SQLite dialect, the MySQL dialect doesn't recognize JSON_OBJECT or other JSON expressions, even though in this case it doesn't have to - no matter how complex the query is, the result is not passed back to Kotlin.
I wish I could add the feature by myself, but I'm pretty new to Kotlin. So my question is: is there a way to evade the rigid syntax check? I could also retrieve from old table, convert the format in Kotlin, then write to the new table, but that would take hundreds of lines of complex code, instead of just one INSERT.
I assume from your links you're on the alpha releases already, in alpha03 you can add currently unsupported behaviour by creating a local SQLDelight module (see this example) and adding the JSON_OBJECT to the functionType override. Also new function types are one of the easiest things to contribute up to SQLDelight so if you want it in the next release
For the record I ended up using CONCAT with COALESCE as a quick and dirty hack to scrape the fields together as JSON.

TypeORM / MySQL - Intercept Update/Insert Queries and set app user ID automatically on 'editedBy' column

I am using TypeORM with MySQL and am setting up automatic auditing of all columns and database tables via MySQL Triggers - not TypeORM's "Logger" feature (unless you have some extra info)...
Without getting bogged down, the MySQL Triggers approach works very well and means no app-side code is required.
The problem: I cannot provide MySQL queries with the logged in app user's ID in a way that does not require we apply it in every query created in this app. We do have a central "CRUD" class, but that is for generic CRUD, so our more "specialist" queries would require special treatment - undesired.
Each of our tables has an int field "editedBy" where we would like to update with the user ID who edited the row (by using our app).
Question: Is there a way to intercept all non-read queries in TypeORM (regardless if its active record or query builder) and be able to update a column in the affected tables ('editedBy' int field)?
This would allow our Triggers solution to be complete.
P.S. I tried out TypeORM's custom logging function:
... typeorm createConnection({ ....
logger: new MyCustomLogger()
... });
class MyCustomLogger { // 'extend' has issue - works without anyway: extends Logger {
logQuery(query, parameters, somethingelse) // WORKS
{ ... }
logQuery does appear to fire before the query (I think) is sent to MySQL, but I cannot find a way how to extract the "Json-like" javascript object out of this, to modify each table's "editedBy". It would be great if there was a way to find all tables within this function and adjust editedBy. Happy to try other options... that don't entail updating the many files we have containing database calls.
Thanks
IMHO it should not be correct to use the logging feature of TypeOrm to modify your queries, it is very dangerous even if it would work with a bit of effort.
If you want to manage the way the upsert queries are done in TypeOrm, the best practice is to use custom repositories and then always calling it (not spawning vanilla repositories aftewards like in entityManager.getRepository(Specialist), instead use yours with entityManager.getCustomRepository(SpecialistRepository)).
The official documentation on the subject should help you a lot: https://github.com/typeorm/typeorm/blob/master/docs/custom-repository.md
Then in your custom repository you can override the save method and add whatever you want. Your code will be explicit and a good advantage is that it does not apply to every entity so if you have other different cases when you want to save differently, you are not stuck (you can also add custom save methods).
If you want to generalize the processing of the save methods, you can create an abstract repository to extend TypeOrm repository that you can then extend with your custom repository, in it you can add your custom code so that you don't end up copying it in every custom repository.
SpecialistRepository<Specialist> -> CustomSaveRepository<T> -> Repository<T>
I used a combination of https://github.com/skonves/express-http-context node module to pass user ID to TypeORM's Event Subscribers feature to make the update to data about to be submitted to DB: https://github.com/typeorm/typeorm/blob/master/sample/sample5-subscribers/subscriber/EverythingSubscriber.ts

How can i get the current schema name with Mybatis?

Basically i need to know if there is any way to get the current schema name using Mybatis.
The DB engine I'm using is MySQL
The most easy way, for which you don't even need to do anything MyBatis-specific, would simply be a query:
SELECT DATABASE();
This should, according to the documentation, return the current database.
Alternatively, you should be able to get the Configuration from your SqlSession via getConfiguration() and get it from there somewhere, perhaps from the environment which allows you access to the DataSource, but you will probably need some database-specific code there.

Grails Change ID type on existing database

I have an existing application in grails using mysql database with much data. The previous programmer uses int as id and I need to change to long as I'm running out of ids. I know that the change in the domain class does not update the column of the existing table. Do I change the type in mysql manually?
There's this thing called database migrations... There's a plugin for it.
http://grails.org/plugin/database-migration
Yes, after changing the domain class change the column manually.
Also, I suppose it's a good idea first to set dbUpdate to e.g. "create-drop" and try it (on another DB instance) to let Grails generate new schema and to see whether it looks as you expect.
So, change the domain, generate test schema and check whether it is correct, then change the original DB manually.

Entity Framework 4.1 Custom Database Initializer strategy

I would like to implement a custom database initialization strategy so that I can:
generate the database if not exists
if model change create only new tables
if model change create only new fields without dropping the table and losing the data.
Thanks in advance
You need to implement IDatabaseInitializer interface.
Eg
public class MyInitializer : IDatabaseInitializer<MyDbContext>
{
public void InitializeDatabase(MyDbContext context)
{
//your logic here
}
}
And then set your initializer at your application startup
Database.SetInitializer<ProductCatalog>(new MyInitializer());
Here's an example
You will have to manually execute commands to alter the database.
context.ObjectContext.ExecuteStoreCommand("ALTER TABLE dbo.MyTable ADD NewColumn VARCHAR(20) NULL");
You can use a tool like SQL Compare to script changes.
There is a reason why this doesn't exist yet. It is very complex and moreover IDatabaseInitializer interface is not very prepared for such that (there is no way to make such initialization database agnostic). Your question is "too broad" to be answered to your satisfaction. With your reaction to #Eranga's correct answer you simply expect that somebody will tell you step by step how to do that but we will not - that would mean we will write the initializer for you.
What you need to do what you want?
You must have very good knowledge of SQL Server. You must know how does SQL server store information about database, tables, columns and relations = you must understand sys views and you must know how to query them to get data about current database structure.
You must have very good knowledge of EF. You must know how does EF store mapping information. You must be able to explore metadata get information about expected tables, columns and relations.
Once you have old database description and new database description you must be able to write a code which will correctly explore changes and create SQL DDL commands for changing your database. Even this look like the simplest part of the whole process this is actually the hardest one because there are many other internal rules in SQL server which cannot be violated by your commands. Sometimes you really need to drop table to make your changes and if you don't want to lose data you must first push them to temporary table and after recreating table you must push them back. Sometimes you are doing changes in constraints which can require temporarily turning constrains off, etc. There is good reason why tools which do this on SQL level (comparing two databases) are probably all commercial.
Even ADO.NET team doesn't implemented this and they will not implement it in the future. Instead they are working on something called migrations.
Edit:
That is true that ObjectContext can return you script for database creation - that is exactly what default initializers are using. But how it could help you? Are you going to parse that script to see what changed? Are you going to execute that script in another connection to use the same code as for current database to see its structure?
Yes you can create a new database, move data from the old database to a new one, delete the old one and rename a new one but that is the most stupid solution you can ever imagine and no database administrator will ever allow that. Even this solution still requires analysis of changes to create correct data transfer scripts.
Automatic upgrade is a wrong way. You should always prepare upgrade script manually with help of some tools, test it and after that execute it manually or as part of some installation script / package. You must also backup your database before you are going to do any changes.
The best way to achieve this is probably with migrations:
http://nuget.org/List/Packages/EntityFramework.SqlMigrations
Good blog posts here and here.