用xml模拟数据库,并实现基本的CURD操作

本文介绍了一种使用DOM4j库实现JavaBean数据持久化的CURD操作方法,包括创建、更新、读取和删除操作,适用于临时替代数据库使用场景。
文件一共有2个,一个接口,一个实现,定义接口是为了以后用其他任意数据库或者其他方法都不用修改其他代码,只要重新设计实现类就Ok了
程序使用了DOM4j BeanUtils Logging 三个第三方jar包

还没有学数据库的平时想做一些数据的CURD可以用这个临时代替一下.


package com.sunsheng.dao.inter;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import com.sunsheng.Exception.IdNotFoundException;

public interface CURD {
        /**
         * 把javabean写入到xml文件中
         * @param record 
         * @throws IOException
         * @throws IllegalAccessException
         * @throws InvocationTargetException
         * @throws NoSuchMethodException
         */
        void create(Object record) throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException;
        
        
        /**
         * 根据指定的id修改xml数据
         * @param id
         * @param record
         * @throws IOException
         * @throws IllegalAccessException
         * @throws InvocationTargetException
         * @throws NoSuchMethodException
         */
        void update(int id, Object record) 
                        throws IOException,
                        IllegalAccessException, 
                        InvocationTargetException, 
                        NoSuchMethodException;
        
        
        /**
         * 获得所有的xml元素
         * @return 返回值是所有bean的list集合
         * @throws IllegalAccessException
         * @throws InvocationTargetException
         * @throws InstantiationException
         */
        List read() 
                        throws IllegalAccessException, 
                        InvocationTargetException, InstantiationException;
        
        
        /**
         * 删除指定id的元素
         * @param id
         * @throws IdNotFoundException
         * @throws IOException
         */
        void delete(int id)
                        throws IdNotFoundException, 
                        IOException;

}

package com.sunsheng.dao.imp;

import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.dom4j.*;
import org.dom4j.io.*;

import com.sunsheng.Exception.IdNotFoundException;
import com.sunsheng.dao.inter.CURD;
import com.sunsheng.domain.Person;

public class XMLImp implements CURD {
        private Document document;
        private Class clazz;

        private static XMLImp instance = new XMLImp();

        private XMLImp() {
                super();
        }

        public static XMLImp getInstance() {
                return instance;
        }

        
        /**
         * 初始化document对象,如果xml不存在,会自动创建一个,根节点默认是records
         * @param clazz 要转换成xml文件的bean的Class
         * @throws DocumentException 
         * @throws IOException
         */
        public void init(Class clazz) throws DocumentException, IOException {
                init(clazz, "records");
        }
        
        
        /**
         * 
         * @param clazz
         * @param root 手动设置根节点的名字
         * @throws DocumentException
         * @throws IOException
         */
        
        public void init(Class clazz, String root) throws DocumentException, IOException {
                this.clazz = clazz;
                SAXReader reader = new SAXReader();
                File file = new File("abc.xml");
                
                //判断文件是否存在
                if (!file.exists()) {
                        //不存在的话,创建一个空文件,留给xml2File方法使用
                        file.createNewFile();
                        
                        //创建一个document对象,往这个对象里面添加一个根元素.
                        document = DocumentHelper.createDocument();
                        document.addElement(root);
                } else
                        //存在就直接读文件
                        document = reader.read(file);

        }

        @Override
        public void create(Object record) throws IOException,
                        IllegalAccessException, InvocationTargetException,
                        NoSuchMethodException {

                // 获得xml文件的根节点
                Element root = document.getRootElement();

                // 根据record得到标签的名字
                String tagName = getTagName();

                // 得到record的id属性
                String value = (BeanUtils.getProperty(record, "id"));

                // 创建一个element,并添加到root下面,设置一个属性id
                Element element = root.addElement(tagName).addAttribute("id", value);

                // 在element下面创建多个子元素用来保存record的每一个属性
                PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(record);
                for (PropertyDescriptor pd : pds) {

                        // 得到属性名,作为子标签名字.
                        String childTagname = pd.getName();

                        // 继承自Object类的class属性不存到xml中
                        if ("class".equals(childTagname))
                                continue;

                        // 得到该属性get方法返回值作为标签的text属性
                        String childTagValue = pd.getReadMethod().invoke(record, null)
                                        .toString();

                        // 用得到的属性名和值添加一个子元素
                        element.addElement(childTagname).addText(childTagValue);
                }

                // 保存xml到文件中
                xml2File();

        }

        @Override
        public void update(int id, Object record) throws IOException,
                        IllegalAccessException, InvocationTargetException,
                        NoSuchMethodException {
                Person person = (Person) record;

                Element element = (Element) document.selectSingleNode("//person[@id="
                                + id + "]");

                for (Iterator iterator = element.elementIterator(); iterator.hasNext();) {
                        Element e = (Element) iterator.next();
                        // 获得标签的名字
                        String name = e.getName();

                        // 通过标签名字得到bean的属性值
                        String text = BeanUtils.getProperty(person, name);

                        // 修改标签的text值
                        e.setText(text);

                }

                xml2File();
        }

        @Override
        public List read() throws IllegalAccessException,
                        InvocationTargetException, InstantiationException {
                List beans = new ArrayList();

                List list = document.selectNodes("//" + getTagName());
                // System.out.println(list);
                for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                        Object bean = clazz.newInstance();

                        Element e = (Element) iterator.next();
                        // 得到元素的所有属性对象
                        List<Attribute> atts = e.attributes();
                        for (Attribute att : atts) {
                                // 遍历每一个属性,按属性名和值设置到对应的bean中
                                BeanUtils.setProperty(bean, att.getName(), att.getValue());

                        }
                        Iterator it = e.elementIterator();
                        while (it.hasNext()) {
                                Element value = (Element) it.next();
                                BeanUtils.setProperty(bean, value.getName(), value.getText());
                        }
                        beans.add(bean);

                }

                return beans;
        }

        @Override
        public void delete(int id) throws IdNotFoundException, IOException {
                // 获得xml文件的根节点
                Node node = document.selectSingleNode("//" + getTagName() + "[@id="
                                + id + "]");
                if (node != null) {
                        node.detach();
                        xml2File();
                } else {

                        throw new IdNotFoundException("您要删除的ID不存在");

                }
        }

        private void xml2File() throws IOException {
                OutputFormat format = OutputFormat.createPrettyPrint();
                XMLWriter writer;
                writer = new XMLWriter(new FileWriter("abc.xml"), format);
                writer.write(document);
                writer.close();

        }

        private String getTagName() {
                String beanName = clazz.getName();
                String tagName = beanName.substring(beanName.lastIndexOf(".") + 1)
                                .toLowerCase();
                return tagName;
        }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值