Java tutorial
/* * Copyright (c) 2017 sainth (sainth@sainth.de) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.sainth.recipe.backend.db.repositories; import de.sainth.recipe.backend.rest.views.Unit; import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import static de.sainth.recipe.backend.db.generated.tables.Units.UNITS; import static org.jooq.impl.DSL.using; @Component public class UnitRepository { private final DSLContext create; @Autowired public UnitRepository(DSLContext create) { this.create = create; } public List<Unit> findAll() { return create .selectFrom(UNITS).fetch().stream().map(record -> new Unit(record.getShortname(), record.getLongname(), record.getConversionFactor(), record.getBasicUnit())) .collect(Collectors.toList()); } public Unit findOne(String shortname) { return create.select(UNITS.SHORTNAME, UNITS.LONGNAME, UNITS.CONVERSION_FACTOR, UNITS.BASIC_UNIT).from(UNITS) .where(UNITS.SHORTNAME.eq(shortname)).fetchOneInto(Unit.class); } public void delete(String shortname) { create.delete(UNITS).where(UNITS.SHORTNAME.eq(shortname)).execute(); } public void deleteAll() { create.deleteFrom(UNITS).execute(); } public Unit save(Unit unit) { AtomicReference<Unit> bu = new AtomicReference<>(); create.transaction(configuration -> { using(configuration) .insertInto(UNITS, UNITS.SHORTNAME, UNITS.LONGNAME, UNITS.CONVERSION_FACTOR, UNITS.BASIC_UNIT) .values(unit.getShortname(), unit.getLongname(), unit.getConversionFactor(), unit.getBasicUnit()) .onConflict().doUpdate().set(UNITS.LONGNAME, unit.getLongname()) .set(UNITS.CONVERSION_FACTOR, unit.getConversionFactor()) .set(UNITS.BASIC_UNIT, unit.getBasicUnit()).execute(); bu.set(using(configuration).selectFrom(UNITS).where(UNITS.SHORTNAME.eq(unit.getShortname())) .fetchOneInto(Unit.class)); }); return bu.get(); } }