Parse xml to initialize the database, parse xml to initialize
To facilitate the development or launch of the project, you may need to initialize the database, including users, permissions, or some other basic data. I use the parsing Xml file to initialize the database.
(1) The Xml file format is as follows:
(2) configure the Servlet for initialization data
Configure in web. xml
<Servlet>
<Servlet-name> PersistenceTest </servlet-name>
<Servlet-class> com. saving. ecm. servlet. PersistenceInitialize </servlet-class>
<Load-on-startup> 2 </load-on-startup>
</Servlet>
(3) load the Servlet when the Tomcat server is started
Public class PersistenceInitialize extends HttpServlet {
Private static final long serialVersionUID = 1L;
Private static final String FILEPATH = "initDataBase. xml ";
@ Override
Public void init () throws ServletException {
Super. init ();
Try {
// If the user data count = 0
Document document = new
SAXReader (). read (Thread. currentThread (). getContextClassLoader ()
. GetResourceAsStream (FILEPATH ));
InitUser (document); // initialize the user
} Catch (Throwable e ){
E. printStackTrace ();
}
}
@ SuppressWarnings ("unchecked ")
Private void initUser (Document document ){
List <Node> childNodes = document. selectNodes ("// users/user ");
CommonAction <User> action = new CommonAction <User> (User. class );
For (Node node: childNodes ){
User user;
Try {
User = action. findById (Long. parseLong (node. valueOf ("@ id ")));
If (user = null ){
User = new User ();
}
User. setAccount (node. valueOf ("@ account "));
User. setName (node. valueOf ("@ name "));
User. setPassword (MD5Util. md5 (node. valueOf ("@ password ")));
User. setEmail (node. valueOf ("@ email "));
User. setRoleCode (node. valueOf ("@ roleCode "));
User. setStatus (node. valueOf ("@ status "));
User. setCreationTime (System. currentTimeMillis ());
Action. saveEntity (user );
} Catch (Throwable e ){
E. printStackTrace ();
}
}
}
}