001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.dao.jdbc.spring;
016    
017    import com.liferay.portal.kernel.dao.jdbc.ParamSetter;
018    import com.liferay.portal.kernel.dao.jdbc.SqlUpdate;
019    
020    import java.sql.Connection;
021    import java.sql.PreparedStatement;
022    import java.sql.SQLException;
023    
024    import javax.sql.DataSource;
025    
026    /**
027     * @author Brian Wing Shun Chan
028     * @author Shuyang Zhou
029     */
030    public class SqlUpdateImpl implements SqlUpdate {
031    
032            public SqlUpdateImpl(
033                    DataSource dataSource, String sql, ParamSetter... paramSetters) {
034    
035                    _dataSource = dataSource;
036                    _sql = sql;
037                    _paramSetters = paramSetters;
038            }
039    
040            @Override
041            public int update(Object... params) throws SQLException {
042                    if (_paramSetters.length != params.length) {
043                            throw new IllegalArgumentException(
044                                    "Expected " + _paramSetters.length + " parameters instead of " +
045                                            params.length + " parameters");
046                    }
047    
048                    try (Connection connection = ConnectionUtil.getConnection(_dataSource);
049                            PreparedStatement preparedStatement = connection.prepareStatement(
050                                    _sql)) {
051    
052                            for (int i = 0; i < _paramSetters.length; i++) {
053                                    ParamSetter paramSetter = _paramSetters[i];
054    
055                                    paramSetter.set(preparedStatement, i + 1, params[i]);
056                            }
057    
058                            return preparedStatement.executeUpdate();
059                    }
060            }
061    
062            private final DataSource _dataSource;
063            private final ParamSetter[] _paramSetters;
064            private final String _sql;
065    
066    }