Project development or on-line stage, for convenience, may need to initialize the database: including users, permissions, or some other basic data. What I'm using here is parsing the Xml file initialization database.
(1) the format of the Xml file is as follows:
(2) Servlet configured to initialize data
Configuring 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) when the Tomcat server starts, the Servlet is loaded
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 user data count = 0
Document document = new
Saxreader (). Read (Thread.CurrentThread (). Getcontextclassloader ()
. getResourceAsStream (FILEPATH));
Inituser (document);// Initialize 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 ();
}
}
}
}
Parsing the XML initialization database