首页 > 代码库 > dom4j解析地址文件并加入mysql数据库示例

dom4j解析地址文件并加入mysql数据库示例

本人使用的是idea的maven工程Mybatis框架演示

 

1.请看下xml树的结构

技术分享

2.首先导入相关jar包并且解决根目录xml文件不加入项目编译问题

<dependencies>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.3</version>
        </dependency>
    </dependencies>
     <build>
             <resources>
                 <resource>
                     <directory>src/main/java</directory>
                     <includes>
                         <include>**/*.properties</include>
                         <include>**/*.xml</include>
                     </includes>
                 </resource>
                 <resource>
                     <directory>src/main/resources</directory>
                 </resource>
             </resources>
         </build>

3.使用mybatis中的逆向工程帮我们做好实体与dao层的操作
  3.1创建mbg.xml文件并放在项目根目录

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--配置jdbc配置源-->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!--把他设置为true 是让它不再自动生成注释-->
            <property name="suppressAllComments" value="http://www.mamicode.com/true" />
        </commentGenerator>
        <!--连接数据库-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/address"
                        userId="root"
                        password="admin">
        </jdbcConnection>
        <!--Java解析类型,我们不用管-->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="http://www.mamicode.com/false" />
        </javaTypeResolver>
        <!--javaBean模型生成--> <!-- 你要把Bean生成在哪个包下--> <!-- 你要在哪个工程下生成.\src代表生成在本工程下-->
        <javaModelGenerator targetPackage="自己所需路径" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="http://www.mamicode.com/true" />
            <property name="trimStrings" value="http://www.mamicode.com/true" />
        </javaModelGenerator>
        <!--指定sqlXML生成映射文件的位置-->
        <sqlMapGenerator targetPackage="自己所需路径"  targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="http://www.mamicode.com/true" />
        </sqlMapGenerator>
        <!--指定Dao接口生成位置,Mapper接口-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="自己所需路径" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="http://www.mamicode.com/true" />
        </javaClientGenerator>
        <!--table元素表示每个表的生成策略-->
        <!--生成表的名称             Bean名称一定要大写    对应的JavaBean的名称-->
        <!--<table tableName="tbuser" domainObjectName="Tbuser"></table>-->
        <table tableName="city" domainObjectName="City"></table>
        <table tableName="community" domainObjectName="Community"></table>
        <table tableName="district" domainObjectName="District"></table>
        <table tableName="province" domainObjectName="Province"></table>
        <table tableName="street" domainObjectName="Street"></table>
        <!--<table tableName="student" domainObjectName="Student"></table>-->
        <!--<table tableName="grade" domainObjectName="Grade"></table>-->
        <!--<table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >-->
            <!--<property name="useActualColumnNames" value="http://www.mamicode.com/true"/>-->
            <!--<generatedKey column="ID" sqlStatement="DB2" identity="true" />-->
            <!--<columnOverride column="DATE_FIELD" property="startDate" />-->
            <!--<ignoreColumn column="FRED" />-->
            <!--<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />-->
        <!--</table>-->
    </context>
</generatorConfiguration>

      3.2接着执行代码生成实体

  

public class TestMBG {
    public static void main(String args[]) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = null;
        config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = null;
        myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

4.当执行完成后会看到我们指定路径下已经生成相应的文件 在这里就不在展示,只要自己设置的路径没错那么在项目中查看即可

5.我们需要在逆向工程中生成的文件做下更改.让我们能够在增加进数据库时能获取当时增加数据的自增ID主键,只示例3个,属性:

  useGeneratedKeys="true" keyProperty="cityid"
 <!--我们调用的是每个实体类DAO的insertSelective方法进行添加,所以打开每个实体类的mapper.xml文件找到方法增加获取增加数据的ID-->
  <insert id="insertSelective" parameterType="entity.Community" useGeneratedKeys="true" keyProperty="communityid">
  <insert id="insertSelective" parameterType="entity.City" useGeneratedKeys="true" keyProperty="cityid">
  <insert id="insertSelective" parameterType="entity.District" useGeneratedKeys="true" keyProperty="districtid">

 

 6.准备工作已完毕,下面开始编写解析方法

public class TestDom4j {


    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;

    private ProvinceMapper provinceMapper;
    private DistrictMapper districtMapper;
    private StreetMapper streetMapper;
    private CityMapper cityMapper;
    private CommunityMapper communityMapper;
    @Before
    public void init(){
        try {
            this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            this.sqlSession = this.sqlSessionFactory.openSession();
            this.provinceMapper = this.sqlSession.getMapper(ProvinceMapper.class);
            this.cityMapper = this.sqlSession.getMapper(CityMapper.class);
            this.districtMapper = this.sqlSession.getMapper(DistrictMapper.class);
            this.streetMapper = this.sqlSession.getMapper(StreetMapper.class);
            this.communityMapper = this.sqlSession.getMapper(CommunityMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void destroy() {
        this.sqlSession.commit();
        this.sqlSession.close();
    }
    @Test
    public void test() {
        SAXReader reader=new SAXReader();
        try {
//          解析文件所在路径
            File file = new File("D:\\dom4jtest1\\src\\test\\All.xml");
            Document document=reader.read(file);
            List<Element> elist = new ArrayList<>();
//            这里是根节点
            Element element=document.getRootElement();
            //获取根节点下一层所有的节点
            elist = element.elements();
            //循环area节点
            for (Element e : elist) {
                //获取area下的所有节点
                List<Element> elist1 = e.elements();
                //new 出省份实例,并且赋值
                Province p = new Province();
                //根据area节点的名称取Text值
                p.setProvincename(e.elementText("name"));
                p.setCode(e.elementText("code"));
                p.setLevel(e.elementText("level"));
                //调用省的增加方法增加完成直接会返回刚才插入数据的对象
                provinceMapper.insertSelective(p);
                //输出刚才插入的数据
                System.out.println("这是省"+p);
                //循环从area下的所有节点
                for (Element e1:elist1){
                    //省份  如:河北省
                    //在这里能够获取area下的所有节点值
//                    System.out.println(e.elementText("name"));
//                    System.out.println("省\t"+e1.getText());
//                    System.out.println("省\t"+e1.getName());
                    //如果在area节点下的子节点有areas节点那么获取子节点下的所有节点
                    if (e1.getName().equals("areas")){
                        //获取areas节点下的所有子节点
                        List<Element> elist2 = e1.elements();
                        //循坏子节点
                        for (Element e2 : elist2) {
                            //在xml中可以看到下一层节点元素内容是城市
                            City city = new City();
                            //对城市属性进行赋值
                            city.setCode(e2.elementText("code"));
                            city.setLevel(e2.elementText("level"));
                            city.setCityname(e2.elementText("name"));
                            city.setProvinceid(p.getProvinceid());
                            cityMapper.insertSelective(city);
                            System.out.println("这是城市"+city);
                            //获取城市以下所有节点
                            List<Element> elist3 = e2.elements();
                            //循坏城市以下节点
                            for (Element e3:elist3){
                                //市辖区 如 北京市
                                //可以在这里不用elementText方法用getText可以获得城市元素的文本
//                                System.out.println("市\t"+e3.getText());
//                                System.out.println("市\t"+e3.getName());
                                /**
                                 * 剩下都一样的思路,请仔细阅读代码方便理解
                                 */
                                if (e3.getName().equals("areas")) {
                                    List<Element> list4 = e3.elements();
                                    for (Element e4 : list4) {
                                        District district = new District();
                                        district.setDistrictname(e4.elementText("name"));
                                        district.setCode(e4.elementText("code"));
                                        district.setLevel(e4.elementText("level"));
                                        district.setCityid(city.getCityid());
                                        int did = districtMapper.insertSelective(district);
                                        System.out.println("这是地区"+district);
                                        List<Element> elist5 = e4.elements();
//                                        System.out.println(elist5.size());
                                        for (Element e5:elist5){
                                            //这里是城区 如:东城区
//                                            System.out.println("地区名称\t"+e5.getName());
//                                            System.out.println("地区名称\t"+e5.getText());
                                            if (e5.getName().equals("areas")) {
                                                //提取所有街道
                                                List<Element> elist6 = e5.elements();
                                                for (Element e6 : elist6) {
                                                    Street street = new Street();
                                                    street.setCode(e6.elementText("code"));
                                                    street.setLevel(e6.elementText("level"));
                                                    street.setStreetname(e6.elementText("name"));
                                                    street.setDistrictid(district.getDistrictid());
                                                    int sid = streetMapper.insertSelective(street);
                                                    System.out.println("这是街道"+street);
                                                    //提取街道下的所有街道名称
                                                    List<Element> elist7 = e6.elements();
                                                    for (Element e7 : elist7) {
                                                        //所有的街道名称
//                                                        System.out.println(e7.getText());
                                                        //是否有下一层居委会
                                                        if (e7.getName().equals("areas")){
                                                            //从街道下提取所有的居委会
                                                            List<Element> elist8 = e7.elements();
                                                            for (Element e8 : elist8) {
                                                                Community comm = new Community();
                                                                comm.setCode(e8.elementText("code"));
                                                                comm.setLevel(e8.elementText("level"));
                                                                comm.setCommunityname(e8.elementText("name"));
                                                                comm.setStreetid(street.getStreetid());
                                                                communityMapper.insertSelective(comm);
                                                                System.out.println("这是居委会"+comm);
                                                                List<Element> elist9 = e8.elements();
                                                                for (Element e9 : elist9) {
                                                                    //输出居委会节点名
//                                                                    System.out.println(e9.getName());
                                                                    //输出居委会名称
//                                                                    System.out.println(e9.getText());
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

7.执行成功,然后查看数据库.

dom4j解析地址文件并加入mysql数据库示例