Unverified Commit 424b4b43 authored by zhaojun's avatar zhaojun Committed by GitHub
Browse files

Merge pull request #131 from betterjava/broadcast-eg

add a raw-jdbc-example for use broadcast-table (left join) 
parents 5444db81 f0661e49
Loading
Loading
Loading
Loading
+60 −0
Original line number Diff line number Diff line
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.example.common.entity;

import java.io.Serializable;

public class Sportsman implements Serializable {

    private static final long serialVersionUID = 663834407582725508L;

    private long id;

    private String name;

    private String countryCode;

    public long getId() {
        return id;
    }

    public void setId(final long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(final String countryCode) {
        this.countryCode = countryCode;
    }

    @Override
    public String toString() {
        return String.format("id: %s, name: %s, countryCode: %s", id, name, countryCode);
    }
}
+23 −0
Original line number Diff line number Diff line
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.example.common.repository;

import org.apache.shardingsphere.example.common.entity.Sportsman;

public interface SportsmanRepository extends CommonRepository<Sportsman, Long> {
}
+152 −0
Original line number Diff line number Diff line
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.example.common.jdbc.repository;

import org.apache.shardingsphere.example.common.entity.Sportsman;
import org.apache.shardingsphere.example.common.repository.SportsmanRepository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

public class SportsmanRepositoryImpl implements SportsmanRepository {

    private final DataSource dataSource;

    public SportsmanRepositoryImpl(final DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void createTableIfNotExists() {
        String sql = "CREATE TABLE IF NOT EXISTS t_sportsman (id BIGINT NOT NULL AUTO_INCREMENT, name VARCHAR(200), country_code VARCHAR(50), PRIMARY KEY (id))";
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        } catch (final SQLException ignored) {
        }
    }

    @Override
    public void dropTable() {
        String sql = "DROP TABLE t_sportsman";
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        } catch (final SQLException ignored) {
        }
    }

    @Override
    public void truncateTable() {
        String sql = "TRUNCATE TABLE t_sportsman";
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        } catch (final SQLException ignored) {
        }
    }

    @Override
    public Long insert(final Sportsman sportsman) {
        String sql = "INSERT INTO t_sportsman (name,country_code) VALUES ( ?, ?)";
        int result = 0;
        try (Connection connection = dataSource.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            preparedStatement.setString(1, sportsman.getName());
            preparedStatement.setString(2, sportsman.getCountryCode());
            result = preparedStatement.executeUpdate();
            try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
                if (resultSet.next()) {
                    sportsman.setId(resultSet.getLong(1));
                }
            }
        } catch (final SQLException ignored) {
        }
        return (long) result;
    }

    @Override
    public void delete(final Long id) {
        String sql = "DELETE FROM t_sportsman WHERE id=?";
        try (Connection connection = dataSource.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setLong(1, id);
            preparedStatement.executeUpdate();
        } catch (final SQLException ignored) {
        }
    }

    @Override
    public List<Sportsman> selectAll() {
        String sql = "SELECT s.id,s.name,s.country_code,c.name,c.language FROM t_sportsman s left join t_country c on s.country_code=c.code";
        return getSportsmen(sql);
    }

    private List<Sportsman> getSportsmen(final String sql) {
        List<Sportsman> result = new LinkedList<>();
        try (Connection connection = dataSource.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                SportsmanExtend sportsman = new SportsmanExtend();
                sportsman.setId(resultSet.getLong(1));
                sportsman.setName(resultSet.getString(2));
                sportsman.setCountryCode(resultSet.getString(3));
                sportsman.setCountryName(resultSet.getString(4));
                sportsman.setCountryLanguage(resultSet.getString(5));
                result.add(sportsman);
            }
        } catch (final SQLException ignored) {
        }
        return result;
    }

    private class SportsmanExtend extends Sportsman {

        private String countryName;

        private String countryLanguage;

        public String getCountryName() {
            return countryName;
        }

        public void setCountryName(final String countryName) {
            this.countryName = countryName;
        }

        public String getCountryLanguage() {
            return countryLanguage;
        }

        public void setCountryLanguage(final String countryLanguage) {
            this.countryLanguage = countryLanguage;
        }

        @Override
        public String toString() {
            return String.format("id: %s, name: %s, countryCode: %s, countryName: %s, countryLanguage: %s", getId(), getName(), getCountryCode(), countryName, countryLanguage);
        }
    }
}
+70 −16
Original line number Diff line number Diff line
@@ -18,7 +18,9 @@
package org.apache.shardingsphere.example.common.jdbc.service;

import org.apache.shardingsphere.example.common.entity.Country;
import org.apache.shardingsphere.example.common.entity.Sportsman;
import org.apache.shardingsphere.example.common.repository.CountryRepository;
import org.apache.shardingsphere.example.common.repository.SportsmanRepository;
import org.apache.shardingsphere.example.common.service.CommonService;

import java.util.ArrayList;
@@ -27,35 +29,51 @@ import java.util.List;
import java.util.Locale;
import java.util.Set;

public class CountryServiceImpl implements CommonService {
public class SportsmanServiceImpl implements CommonService {

    private final CountryRepository countryRepository;

    public CountryServiceImpl(final CountryRepository countryRepository) {
    private final SportsmanRepository sportsmanRepository;

    public SportsmanServiceImpl(final CountryRepository countryRepository, final SportsmanRepository sportsmanRepository) {
        this.countryRepository = countryRepository;
        this.sportsmanRepository = sportsmanRepository;
    }

    @Override
    public void initEnvironment() {
        countryRepository.createTableIfNotExists();
        sportsmanRepository.createTableIfNotExists();
        countryRepository.truncateTable();
        sportsmanRepository.truncateTable();
    }

    @Override
    public void cleanEnvironment() {
        countryRepository.dropTable();
        sportsmanRepository.dropTable();
    }

    @Override
    public void processSuccess() {
        System.out.println("-------------- Process Success Begin ---------------");
        List<String> countryCodes = insertData();
        InsertResult insertResult = insertData();
        printData();
        deleteData(countryCodes);
        deleteData(insertResult);
        printData();
        System.out.println("-------------- Process Success Finish --------------");
    }

    private void deleteData(final InsertResult insertResult) {
        System.out.println("---------------------------- Delete Data ----------------------------");
        for (String each : insertResult.getCountryCodes()) {
            countryRepository.delete(each);
        }
        for (Long each : insertResult.getSportsmanIds()) {
            sportsmanRepository.delete(each);
        }
    }

    @Override
    public void processFailure() {
        System.out.println("-------------- Process Failure Begin ---------------");
@@ -64,23 +82,27 @@ public class CountryServiceImpl implements CommonService {
        throw new RuntimeException("Exception occur for transaction test.");
    }

    @Override
    public void printData() {
        System.out.println("---------------------------- Print Country Data -------------------");
        for (Object each : countryRepository.selectAll()) {
            System.out.println(each);
        }
    private InsertResult insertData() {
        System.out.println("---------------------------- Insert Data ----------------------------");
        List<String> countryCodes = insertCountry();
        List<Long> sportsmanIds = insertSportman(countryCodes);
        return new InsertResult(countryCodes, sportsmanIds);
    }

    private void deleteData(final List<String> countryCodes) {
        System.out.println("---------------------------- Delete Data ----------------------------");
        for (String each: countryCodes) {
            countryRepository.delete(each);
    private List<Long> insertSportman(final List<String> countryCodes) {
        List<Long> result = new ArrayList<>(countryCodes.size());
        int index = 0;
        for (String countryCode : countryCodes) {
            Sportsman sportsman = new Sportsman();
            sportsman.setName("test_" + ++index);
            sportsman.setCountryCode(countryCode);
            sportsmanRepository.insert(sportsman);
            result.add(sportsman.getId());
        }
        return result;
    }

    private List<String> insertData() {
        System.out.println("---------------------------- Insert Data ----------------------------");
    private List<String> insertCountry() {
        Set<String> result = new LinkedHashSet<>();
        for (Locale each : Locale.getAvailableLocales()) {
            if (result.contains(each.getCountry()) || each.getCountry().isEmpty()) {
@@ -98,4 +120,36 @@ public class CountryServiceImpl implements CommonService {
        }
        return new ArrayList<>(result);
    }

    @Override
    public void printData() {
        System.out.println("---------------------------- Print Country Data -------------------");
        for (Object each : countryRepository.selectAll()) {
            System.out.println(each);
        }
        System.out.println("---------------------------- Print Sportman Data -----------------------");
        for (Object each : sportsmanRepository.selectAll()) {
            System.out.println(each);
        }
    }

    private class InsertResult {

        private final List<String> countryCodes;

        private final List<Long> sportsmanIds;

        InsertResult(final List<String> countryCodes, final List<Long> sportsmanIds) {
            this.countryCodes = countryCodes;
            this.sportsmanIds = sportsmanIds;
        }

        public List<Long> getSportsmanIds() {
            return sportsmanIds;
        }

        public List<String> getCountryCodes() {
            return countryCodes;
        }
    }
}
+3 −2
Original line number Diff line number Diff line
@@ -23,7 +23,8 @@ package org.apache.shardingsphere.example.broadcast.table.raw.jdbc;

import org.apache.shardingsphere.example.broadcast.table.raw.jdbc.config.ShardingDatabasesConfiguration;
import org.apache.shardingsphere.example.common.jdbc.repository.CountryRepositoryImpl;
import org.apache.shardingsphere.example.common.jdbc.service.CountryServiceImpl;
import org.apache.shardingsphere.example.common.jdbc.repository.SportsmanRepositoryImpl;
import org.apache.shardingsphere.example.common.jdbc.service.SportsmanServiceImpl;
import org.apache.shardingsphere.example.common.service.CommonService;

import javax.sql.DataSource;
@@ -40,6 +41,6 @@ public class JavaConfigurationExample {
    }

    private static CommonService getCountryService(final DataSource dataSource) {
        return new CountryServiceImpl(new CountryRepositoryImpl(dataSource));
        return new SportsmanServiceImpl(new CountryRepositoryImpl(dataSource), new SportsmanRepositoryImpl(dataSource));
    }
}
Loading