项目的研发或者上线阶段,为了方便,可能需要初始化数据库:包括用户,权限,或者一些其他的基础数据。我这里采用的是解析Xml文件初始化数据库。
(1)Xml文件的格式如下:
(2)配置初始化数据的Servlet
在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)Tomcat服务器启动时,加载Servlet
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 {
//如果用户数据count = 0
Document document = new
SAXReader().read(Thread.currentThread().getContextClassLoader()
.getResourceAsStream(FILEPATH));
initUser(document);// 初始化用户
} 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();
}
}
}
}
原文:http://blog.csdn.net/u013628152/article/details/42391695