1 Star 0 Fork 0

OSCHINA-MIRROR/chyxion-newbie-jdbc

Join Gitlife
Discover and participate in excellent open source projects with over 10 million developers. Private repositories are also completely free :)
Join for free
Clone/Download
Contribute code
Sync code
Cancel
Hint: Since Git does not support empty folders, creating a folder will generate an empty .keep file.
Loading...
README.md

Newbie JDBC — это простой инструмент JDBC. Он поддерживает расширение параметров массива, совместное использование соединения, транзакции, нумерацию страниц и т. д.

Использование

Добавить зависимость Maven

<dependency>
    <groupId>me.chyxion</groupId>
    <artifactId>newbie-jdbc</artifactId>
    <version>0.0.2-RELEASE</version>
</dependency>

Использовать в коде

Создать объект Newbie JDBC

// инициализировать источник данных, здесь используется DruidDataSource в качестве демонстрации
DruidDataSource datasource = null;
datasource = new DruidDataSource();
datasource.setUrl("jdbc:mysql://127.0.0.1/demo");
datasource.setUsername("root");
datasource.setPassword("password");
datasource.init();

// создать объект NewbieJdbc
NewbieJdbc jdbc = new NewbieJdbcImpl(datasource);

Базовый запрос

// количество пользователей
int count = jdbc.findValue(
    "select count(1) from users");

// найти имя пользователя с идентификатором 2008110101
String name = jdbc.findValue(
    "select name from users where id = ?", 
    "2008110101");

// найти имена пользователей с идентификаторами 101 или 102
// 0. массив в качестве параметров
List<String> names = jdbc.listValue(
    "select name from users where id in (?)", 
    "101", "102");

// 1. коллекция в качестве параметров
names = jdbc.listValue(
    "select name from users where id in (?)", 
    Arrays.asList("101", "102"));

// 2. карта в качестве параметров
Map<String, Object> params = 
    new HashMap<String, Object>();
params.put("id", Arrays.asList("101", "102"));
// или: 
// params.put("id", new String[] {"101", "102"});
names = jdbc.listValue(
    "select name from users where id in (:id)", 
    params);

// найти пользователя с идентификатором 101
Map<String, Object> mapUser = jdbc.findMap(
    "select id, name, gender from users where id = ?", "101");

// список пользователей возраста 24
List<Map<String, Object>> listUsers = jdbc.listMap(
    "select id, name, gender from users where age = ?", 24);

Расширенный запрос

// найти идентификатор и имя в виде строкового массива
String[] idAndName = jdbc.findOne(new Ro<String[]>() {
        public String[] exec(ResultSet rs) throws SQLException {
            return new String[] {
                rs.getString("id"), 
                rs.getString("name")};
        }
    },
    "select id, name from users where id = ?", 
    "101");

// найти имена пола M
String names = jdbc.list(new Ro<String>() {
        public String exec(ResultSet rs) throws SQLException {
            return rs.getString("name");
        }
    }, 
    "select name from users where gender = ?", 
    "M");

// найти имя пользователя с идентификатором 101, аналогично findValue
String name = jdbc.query(new Ro<String>() {
    public String exec(ResultSet rs) throws SQLException {
            return rs.next() ? rs.getString(1) : null;
        }
    }, 
    "select name from users where id = ?", 
    "101");

// список пользователей пола F со смещением 10 и ограничением 16
List<Map<String, Object>> users =
    jdbc.listMapPage(
       "select * from users where gender = ?", 
        Arrays.asList(new Order("date_created", Order.DESC)), 
        10, 16, "F");

Вставка и обновление

// вставить один
Map<String, Object> mapUser = new HashMap<String, Object>();
mapUser.put("id", "103");
mapUser.put("name", "Shaun Chyxion");
mapUser.put("gender", "M");
mapUser.put("date_created", new Date());
jdbc.insert("users", mapUser);

// вставить пакет
Collection<Collection<?>> users = 
    Arrays.<Collection<?>>asList(
        Arrays.<Object>asList("104", "Xuir", "F", new Date()), 
        Arrays.<Object>asList("105", "Sorina Nyco", "F", new Date()), 
        Arrays.<Object>asList("106", "Gemily", "F", new Date()), 
        Arrays.<Object>asList("107", "Luffy", "M", new Date()), 
        Arrays.<Object>asList("108", "Zoro", "M", new Date()), 
        Arrays.<Object>asList("109", "Bruck", "M", new Date()));
jdbc.insert("users", 
    Arrays.asList("id", "name", "gender", "date_created"), 
    args, 3);

// обновить пол на F для пользователя 102
jdbc.update("update users set gender = ? where id = ?", "F", "102");

Повторное использование подключения и транзакции

// найти пользователя с идентификатором 101 и книги используют то же подключение
Map<String, Object> mapUserWithBooks jdbc.execute(new Co<Map<String, Object>>() {
    @Override
    protected Map<String, Object> run() throws SQLException {
        String userId = "101";
        Map<String, Object> mapRtn = findMap(
            "select * from users where id = ?", userId);
        mapRtn.put("books", 
            listMap("select * from books where user_id = ?", 
                userId));
        return mapRtn;
    }
});

// Выполнить транзакцию
Map<String, Object> mapUser = 
jdbc.executeTransaction(new Co<Map<String, Object>>() {
    @Override
    protected Map<String, Object> run() throws SQLException {
        update("delete users where id = ?", "104");
        update("update users set age = ? where id = ?", 24, "103");
        return findMap("select * from users where id = ?", 106);
    }
});

### Выполнение SQL
```java
// Создать таблицу users
jdbc.execute(
    "create table users (" + 
    "id varchar(36) not null, " + 
    "name varchar(36) not null, " + 
    "primary key (id))");

Настройка Newbie JDBC

// Создание таблицы users
CustomResolver customResolver = new CustomResolver() {
    // Установить StringBuilder как String
    public void setParam(PreparedStatement ps, 
            int index, Object param)
            throws SQLException {
        if (param instanceof StringBuilder) {
            ps.setString(index, param.toString());
        }
        else {
            ps.setObject(index, param);
        }
    }

    // Чтение CLOB как String
    public Object readValue(ResultSet rs, int index) 
            throws SQLException {
        Object valueRtn = null;
        if (Types.CLOB == rs.getMetaData().getColumnType(index)) {
            valueRtn = rs.getClob(index).toString();
        }
        else {
            valueRtn = rs.getObject(index);
        }
        return valueRtn;
    }

    // Использование MySQLCompatiblePaginationProcessor для разбиения на страницы
    public PaginationProcessor getPaginationProcessor(
            Connection conn) {
        return new MySQLCompatiblePaginationProcessor();
    }
};

jdbc = new NewbieJdbcSupport(dataSource, customResolver);

Contacts

chyxion@163.com

Comments ( 0 )

You can comment after Login

Introduction

Нубик ДжейСиБиСи Expand Collapse
MIT
Cancel

Releases

No releases yet

Contributor

All

Recent Activities

Load more
No more results to load
1
https://gitlife.ru/oschina-mirror/chyxion-newbie-jdbc.git
git@gitlife.ru:oschina-mirror/chyxion-newbie-jdbc.git
oschina-mirror
chyxion-newbie-jdbc
chyxion-newbie-jdbc
master