Springboot+hibernate 操作原生sql语句实现建表和插入数据

先看配置文件 


spring:
  datasource:
    url: (你的数据库地址)
    username: (用户名)
    password: (密码)
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext


前台Html

这里我是创建表,并且上传csv的数据

<form action="tableactive/submitTable" method="post" id="nextSave">
			<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
				<div class="modal-dialog" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
							<h4 class="modal-title" id="myModalLabel">创建表</h4>
						</div>
						<div class="modal-body">

							<p>表名</p>
							<div class="input-group input-group-sm">
								<input type="text" class="form-control" placeholder="请输入表名" aria-describedby="sizing-addon3" style="width:565px;" name="tableName">
							</div>

							<p style="margin-top:15px">保存时长(天)</p>
							<div class="input-group input-group-sm">
								<input name="activeTime" type="text" class="form-control" placeholder="请输入保存时长" aria-describedby="sizing-addon3" style="width:565px;" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
							</div>

							<p style="margin-top:15px">表结构</p>
							<a class="glyphicon glyphicon-plus-sign" onclick="addrow()">添加一行</a>
							<table class="table table-bordered" id="tablestru">
								<tr>
									<td>列名</td>
									<td>类型</td>
									<td></td>
									<tr>
							</table>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-primary" onclick="nextMyModal()">下一步</button>
							<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						</div>
					</div>
				</div>
			</div>

			<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
				<div class="modal-dialog" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
							<h4 class="modal-title" id="myModalLabel">上传数据</h4>
						</div>
						<div class="modal-body">
							<button type="button" class="btn btn-primary" style="width:570px;text-align:center;" id="selectFileBtn">
             	  <span class="glyphicon glyphicon-folder-open" id="FileBtnName"> 上传文件</span>
              </button>
							<input type="file" class="hidden" name="file" accept=".csv" id="selectFileInput" />
							<p style="text-align:center;margin-top:15px;font-size: 15px;">请上传.csv文件</p>
							<input type="text" style="display:none;" name="fileAdress" id="fileAdress" />
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-primary" id="formSubmit">保存</button>
							<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						</div>
					</div>
				</div>
			</div>

		</form>
js代码js代码 
 
function addrow(){


	var tables = $('#tablestru');
	var addtr = $("<tr>"
    +'<td style="text-align:center;width:50%"><input style="width:96%" name="columnName"></input></td>'
    +'<td style="text-align:center;width:30%">'
    +'<select style="width:96%" name="kindName">'
    +'<option value="bigint">bigint</option>'
    +'<option value="double">double</option>'
    +'<option value="decimal">decimal</option>'
    +'<option value="varchar">varchar</option>'
    +'<option value="boolean">boolean</option>'
    +'<option value="datetime">datetime</option>'
    +' </select>'
    +'</td>'
    +'<td style="text-align:center;width:20%"><a class="glyphicon glyphicon-remove-circle" onclick="deleteTrRow(this)">删除</a></td>'
    +'<tr>');
    addtr.appendTo(tables);     
 
	}




 function deleteTrRow(tr){


    $(tr).parent().parent().remove();


    }
 
 function nextMyModal(){
	 $('#myModal2').modal('show');
	 $('#myModal').modal('hide');
 }
 
 $("#selectFileBtn").click(function () {
     $("#selectFileInput").click();
 });


 $("#selectFileInput").fileupload({
     url: '/tableactive/uploadFile',
     dataType: 'json',
     done: function (e, data) {
         $("#upload-modal-btn").click();
         $('.progress-bar').css('width', '0');
         $('.progress').addClass('hidden');
         $('.percentage').addClass('hidden');
         $("#error_message").text("");
         if (data.result.code === 200) {
           //这里需要将地址转码
        	 document.getElementById("fileAdress").value =data.result.detail.address ;
        	 document.getElementById("FileBtnName").innerHTML =" 上传成功" ;
         } else {
        	 alert(data.result.detail);
         }
     }
 });


$("#formSubmit").click(function(){
	
	$("#nextSave").ajaxSubmit(function(data){    
		 if (data.code === 200) {
	           //这里需要将地址转码
			 $('#myModal2').modal('hide');
			 $('#myModal').modal('hide');
			 alert(data.detail);
	         } else {
	        	 alert(data.detail);
	         }
    });   
	
})
@RestController
@RequestMapping("/tableactive")
public class TableactiveController {

	private final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private TableactiveService tableactiveService;
	@Autowired
	private FileUtil fileUtil;
	@Autowired
	private SiteConfig siteConfig;
	
	
	@GetMapping("/getPage")
	public ReplyInfo getNodes(HttpServletRequest req) {
		List<Tableactive> data = tableactiveService.getfindAll();
		return new ReplyInfo(true, data);
	}
	
	@PostMapping("/submitTable")
	public Result submitTable(HttpServletRequest req, String columnName,String tableName,String kindName,String activeTime,String fileAdress) {
		String[] columnNameArray=columnName.split(",");
		String[] kindNameArray=kindName.split(",");
		boolean init=tableactiveService.createTable(columnNameArray, kindNameArray, tableName, activeTime);
		if(init) {
			boolean insert=	tableactiveService.insertTableActive(tableName,activeTime);
			if(insert) {
				boolean insertSql=tableactiveService.insertSqlForDb(fileAdress, tableName);
				if(!insertSql) {
					return Result.error("插入数据不正确");
				}
				
				tableactiveService.deleteFile(fileAdress);
				
			}else {
				return Result.error("表名或保存时长填写有误");
			}
		}else {
			return Result.error("创建数据库表出错");
		}
		return Result.success("保存成功");
	}
		
	@PostMapping("/uploadFile")
	@ResponseBody
	public Result uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		if (!file.isEmpty()) {
			try {
				String requestUrl = fileUtil.uploadFile(file, FileUploadEnum.FILE);
				Map<String, String> map = new HashMap<>();
				map.put("address", requestUrl);
				map.put("fileName", file.getOriginalFilename());
				map.put("serverHost", siteConfig.getBaseUrl());
				return Result.success(map);
			} catch (IOException e) {
				e.printStackTrace();
				return Result.error("上传失败");
			}
		}
		return Result.error("文件不存在");
	}

	/**
	 * 下载文件
	 * 
	 * @param fileName
	 * @param response
	 * @return
	 */
	@GetMapping("/downloadFile")
	@ResponseBody
	public Result downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response,
			HttpServletRequest req) {
		Boolean flag = fileUtil.download(fileName, response, req);
		if (!flag) {
			return Result.error("下载失败");
		}
		return null;
	}
	
	

}

TableactiveService

@Service
public class TableactiveService {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private TableactiveRepository tableactiveRepository;


	public List<Tableactive> getfindAll() {
		return tableactiveRepository.findAll();
	}
	
	
	public boolean insertTableActive(String tableName,String activeTime) {
		try {
		 int actTime=Integer.valueOf(activeTime);
		 Date d = new Date();
		 Calendar ca = Calendar.getInstance();
		 ca.add(Calendar.DATE, actTime);
		 d = ca.getTime();
		 Tableactive tableactive=new Tableactive();
		 tableactive.setActiveTime(d);
		 tableactive.setTableName(tableName);
		 tableactiveRepository.save(tableactive);
		}catch(Exception e){
			log.error("insertTableActive error::", e);
			return false;
		}
		 return true;
	}
	
	
	public boolean createTable(String[] columnNameArray,String[] kindNameArray,String tableName,String activeTime) {
		try {
		String sql="CREATE TABLE `"+ tableName+"`(";
		String culunmName="";
		String kindName="";
		int fieldLength=0;
		int pointLength=0;
		for(int i=0;i<columnNameArray.length;i++) {
			culunmName=columnNameArray[i];
			kindName=kindNameArray[i];
			if(kindName.equals("bigint")) {
				fieldLength=20;
			}else if(kindName.equals("double")) {
				fieldLength=16;
				pointLength=2;
			}else if(kindName.equals("decimal")) {
				fieldLength=65;
				pointLength=30;
			}else if(kindName.equals("varchar")) {
				fieldLength=255;
			}else if(kindName.equals("boolean")) {
				fieldLength=1;
				kindName="tinyint";
			}else if(kindName.equals("datetime")) {
				fieldLength=0;
			}
			
			if(pointLength==0) {
			sql=sql+"`" +culunmName+"` "+kindName+"("+fieldLength+"),";
			}else {
			sql=sql+"`" +culunmName+"` "+kindName+"("+fieldLength+","+pointLength+"),";
			}
			if(i==columnNameArray.length-1) {
				sql=sql.substring(0,sql.length()-1)+" )";
			}
		}
		queryBysql(sql);
		}catch(Exception e) {
			log.error("createTable error::", e);
			return false;
		}
		return true;
	}
	
	
	public boolean insertSqlForDb(String filePath,String tableName) {
		try { 
			BufferedReader reader = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null; 
            while((line=reader.readLine())!=null){ 
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值
                String sqlTemp="INSERT INTO `"+tableName+"` VALUES (";
                for(int i=0;i<item.length;i++) {
                	
                	if(i==item.length-1) {
                		sqlTemp=sqlTemp+"'"+item[i]+"');";
                		continue;
                	}
                	sqlTemp=sqlTemp+"'"+item[i]+"',";
                }
                queryBysql(sqlTemp);
            } 
           
        } catch (Exception e) { 
        	log.error("insertSqlForDb error::", e);
            return false;
        } 
		return true;
	}
	
	
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;


	@Transactional
	public  void queryBysql(String sql) {
		 sessionFactory.openSession().createSQLQuery(sql).executeUpdate();
		
	}
	
	 public static void deleteFile(String filePath) {
	        File file = new File(filePath);
	        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
	        if (file.exists() && file.isFile()) {
	        	 file.delete();
	        }
	    }
	
}
@Component
public class FileUtil {

	@Autowired
	private SiteConfig siteConfig;
	public static final String FORMAT_DATE = "yyyy-MM-dd";
	
	
	public static String formatDate(Date date) {
	    if (date == null) return null;
	    SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
	    sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
	    return sdf.format(date);
	  }
	/**
	 * upload file
	 *
	 * @param file
	 * @param fileUploadEnum
	 * @return
	 * @throws IOException
	 */
	public String uploadFile(MultipartFile file, FileUploadEnum fileUploadEnum) throws IOException {
		if (!file.isEmpty()) {
			String originalFilename= file.getOriginalFilename();
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//			String type = file.getContentType();
//			String suffix = "." + type.split("/")[1];
			String fileName = null;
			BufferedOutputStream stream = null;
			String requestPath = null;

			// upload file
			if (fileUploadEnum == FileUploadEnum.FILE) {
				String today = formatDate(new Date());
				String userUploadPath =   today + "/";
//				fileName = UUID.randomUUID().toString() + suffix;
				fileName = originalFilename;
				File file_dir = new File(siteConfig.getUploadPath() + userUploadPath);
				if (!file_dir.exists())
					file_dir.mkdirs();
				stream = new BufferedOutputStream(
						new FileOutputStream(new File(siteConfig.getUploadPath() + userUploadPath + fileName)));
				requestPath = siteConfig.getBbsStaticUrl() + userUploadPath;
				if (stream != null) {
					stream.write(file.getBytes());
					stream.close();
					return siteConfig.getUploadPath() + userUploadPath + fileName;
				}
			}

			// upload avatar (image)
			if (fileUploadEnum == FileUploadEnum.AVATAR) {
				String today = formatDate(new Date());
				String userUploadPath =  today + "/";
				fileName = UUID.randomUUID().toString() + suffix;
				File file_dir = new File(siteConfig.getUploadPath() + userUploadPath);
				if (!file_dir.exists())
					file_dir.mkdirs();
				stream = new BufferedOutputStream(
						new FileOutputStream(new File(siteConfig.getUploadPath() + userUploadPath + fileName)));
				requestPath = siteConfig.getBbsStaticUrl() + userUploadPath;
				if (stream != null) {
					stream.write(file.getBytes());
					stream.close();
				return requestPath + fileName;
				}
			}
		}
		return null;
	}

	public static String encodeURIComponent(String value) {
		try {
			return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}


	public Boolean download(String fileName, HttpServletResponse response, HttpServletRequest req) {
		if (fileName != null) {
			String realFileName  = fileName.substring(fileName.lastIndexOf("/")+1);
			String realPath = fileName.substring(0, fileName.lastIndexOf("/")+1);
			
			File file = new File(realPath, realFileName);
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				String filenamedisplay = realFileName;
				String headerValue = "attachment;";
				headerValue += " filename=\"" + encodeURIComponent(filenamedisplay) +"\";";
				headerValue += " filename*=utf-8''" + encodeURIComponent(filenamedisplay);
				response.setHeader("Content-Disposition", headerValue);
				response.setContentType("application/octet-stream");
				response.setCharacterEncoding("UTF-8");
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("success");
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				return true;
			}
		}
		return false;
	}
	
	
	
	/**
	 * search username upload dir's space size
	 *
	 * @param file
	 * @return
	 */
	public long getTotalSizeOfFilesInDir(File file) {
		if (file.isFile())
			return file.length();
		File[] children = file.listFiles();
		long total = 0;
		if (children != null)
			for (File child : children)
				total += getTotalSizeOfFilesInDir(child);
		return total;
	}
}


@Configuration
@ConfigurationProperties(prefix = "site")
public class SiteConfig {

	private String uploadPath;
	private String bbsStaticUrl;
	private String baseUrl;
	
	
	
	
	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public String getBbsStaticUrl() {
		return bbsStaticUrl;
	}

	public void setBbsStaticUrl(String bbsStaticUrl) {
		this.bbsStaticUrl = bbsStaticUrl;
	}

	public String getUploadPath() {
		return uploadPath;
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

	

}

猜你喜欢

转载自blog.csdn.net/qq_36666181/article/details/80496299