001/* 002 * JKNIV, whinstone one contract to access your database. 003 * 004 * Copyright (C) 2017, the original author or authors. 005 * 006 * This library is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 2.1 of the License. 010 * 011 * This library is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public 017 * License along with this library; if not, write to the Free Software Foundation, Inc., 018 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 019 */ 020package net.sf.jkniv.whinstone.jdbc.commands; 021 022import java.sql.Connection; 023import java.sql.PreparedStatement; 024import java.sql.ResultSet; 025import java.sql.SQLException; 026import java.util.ArrayList; 027import java.util.Iterator; 028import java.util.List; 029 030import org.slf4j.Logger; 031 032import net.sf.jkniv.exception.HandleableException; 033import net.sf.jkniv.sqlegance.Insertable; 034import net.sf.jkniv.whinstone.Queryable; 035import net.sf.jkniv.whinstone.statement.AutoKey; 036 037/** 038 * Call an database sequence and put the value into parameter object from {@link Queryable} 039 * 040 * @author Alisson Gomes 041 * @since 0.6.0 042 */ 043public class JdbcSequenceGeneratedKey implements AutoKey<Object> 044{ 045 private static final Logger SQLLOG = net.sf.jkniv.whinstone.jdbc.LoggerFactory.getLogger(); 046 047 private List<Object> keys; 048 049 public JdbcSequenceGeneratedKey(Insertable isql, Connection conn, HandleableException handlerException) 050 { 051 this.keys = new ArrayList<Object>(); 052 try 053 { 054 String query = isql.getAutoGeneratedKey().getText(); 055 SQLLOG.info(query); 056 PreparedStatement stmt = conn.prepareStatement(query); 057 ResultSet generatedKeys = stmt.executeQuery(); 058 while (generatedKeys.next()) 059 { 060 Object id = generatedKeys.getObject(1); 061 this.keys.add(id); 062 } 063 } 064 catch (SQLException e) 065 { 066 handlerException.handle(e); 067 } 068 } 069 070 @Override 071 public Object getId() 072 { 073 if (isEmpty()) 074 return null; 075 076 return (Long) this.keys.get(0); 077 } 078 079 @Override 080 public String getUId() 081 { 082 if (isEmpty()) 083 return null; 084 085 return String.valueOf(this.keys.get(0)); 086 } 087 088 @Override 089 public Iterator<Object> iterator() 090 { 091 return this.keys.iterator(); 092 } 093 094 @Override 095 public boolean hasItem() 096 { 097 return this.keys.size() > 0; 098 } 099 100 @Override 101 public boolean isEmpty() 102 { 103 return this.keys.isEmpty(); 104 } 105 106 @Override 107 public int size() 108 { 109 return this.keys.size(); 110 } 111 112}