Spring JdbcTemplate - Insert blob and return generated key

后端 未结 11 1840
猫巷女王i
猫巷女王i 2020-12-15 06:06

From the Spring JDBC documentation, I know how to insert a blob using JdbcTemplate

final File blobIn = new File(\"spring2004.jpg\");
final InputStream blobIs         


        
11条回答
  •  情话喂你
    2020-12-15 06:32

    package com.technicalkeeda.dao;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.sql.Types;
    
    import javax.sql.DataSource;
    
    import org.springframework.dao.DataAccessException;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.support.SqlLobValue;
    import org.springframework.jdbc.support.lob.DefaultLobHandler;
    import org.springframework.jdbc.support.lob.LobHandler;
    
    public class ImageDaoImpl implements ImageDao {
    
        private DataSource dataSource;
    
        private JdbcTemplate jdbcTemplate;
    
        public void setDataSource(DataSource dataSource) {
            this.dataSource = dataSource;
            this.jdbcTemplate = new JdbcTemplate(this.dataSource);
        }
    
        @Override
        public void insertImage() {
            System.out.println("insertImage" + jdbcTemplate);
    
            try {
                final File image = new File("C:\\puppy.jpg");
                final InputStream imageIs = new FileInputStream(image);
    
                LobHandler lobHandler = new DefaultLobHandler(); 
    
                jdbcTemplate.update(
                         "INSERT INTO trn_imgs (img_title, img_data) VALUES (?, ?)",
                         new Object[] {
                           "Puppy",
                           new SqlLobValue(imageIs, (int)image.length(), lobHandler),
                         },
                         new int[] {Types.VARCHAR, Types.BLOB});
    
    
            } catch (DataAccessException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
        }
    }
    

提交回复
热议问题