Thursday 15 January 2015

java - replacement for import.sql file in spring/hibernate project -



java - replacement for import.sql file in spring/hibernate project -

in spring projects, have hibernate configured create tables in database based on entity classes. also, when need insert initial values on tables, set file named import.sql on classpath sql commands insert info in database. wonder if there way accomplish import feature without need place import.sql file within project, using java classes. knows if possible?

you can consider 2 alternatives,

first 1 not java only, since you're using stack, can consider spring dbunit

@runwith(springjunit4classrunner.class) @contextconfiguration(locations = {"/context.xml"}) @testexecutionlisteners({dependencyinjectiontestexecutionlistener.class, dirtiescontexttestexecutionlistener.class, transactionaltestexecutionlistener.class, dbunittestexecutionlistener.class}) @dbunitconfiguration(datasetloader = columnsensingflatxmldatasetloader.class) public class templateit { @before public void after() throws exception { idatabaseconnection connection; idatabasetester databasetester = new jdbcdatabasetester(jdbc_driver, jdbc_url + "&sessionvariables=foreign_key_checks=0", user, jdbc_password); connection = databasetester.getconnection(); querydataset partialdataset = new querydataset(connection); databaseoperation.delete_all.execute(connection, partialdataset); } @databasesetup("../dbunit/data.xml") @expecteddatabase("../dbunit/expected.xml") @test public void testdbunit() throws exception { ... } }

the info handled through xml, library focused around test offers many utilities outmatch dealing sql directly. easier dealing partial data, simplified assertion @expecteddatabase etc.

secondly, 1 "java only" setup utilize prepare info through hibernate entities. i'm assuming you're using generic daos, if not, easy set up. in @before methods of test set db you're liking, snippet

@before public void before() throws daoexception { company company = new company(); companydao.makepersistent(company); }

i favour approach in view increases portability (often utilize in memory dbs testing), readability , maintaince. downside lot of code in tests, , preparing info can tedious complex objects.

java spring hibernate spring-mvc

No comments:

Post a Comment