一开始是一个例子(前台到后台),上传数据新建数据表以及插入数据,如果不需要,可直接拉到最后看关键代码和简要代码
先看配置文件
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
package com.mlcp.config;
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
public class HibernateAutoConfiguration {
@Bean
public SessionFactory sessionFactory(EntityManagerFactory factory) {
if (factory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return factory.unwrap(SessionFactory.class);
}
}
前台Html
这里我是创建表,并且上传csv的数据
js代码
function addrow(){
var tables = $('#tablestru');
var addtr = $(""
+' '
+''
+''
+' '
+'删除 '
+' ');
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 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 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 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 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
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;
}
}
简要代码(查询):
/**
*
* @param sourceName
* @param kindName
* @return
*/
public List fieldColumnName(String sourceName,String kindName){
String sql="select COLUMN_NAME from information_schema.COLUMNS where table_name = '"+sourceName+"' and DATA_TYPE='"+kindName+"'";
return queryBysql(sql);
}
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
@Transactional
public List queryBysql(String sql) {
return sessionFactory.openSession().createSQLQuery(sql).list();
}
简要代码(插入,建表)
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
@Transactional
public void queryBysql(String sql) {
@Transactional
public void queryBysql(String sql) {
Transaction transaction = null;
Session session = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.createSQLQuery(sql).executeUpdate();
transaction.commit();
} catch (Exception e) {
transaction.rollback();
} finally {
session.close();
}
}
}
关键代码
spring:
datasource:
url: jdbc:mysql://localhost:3306/mlcp?useSSL=false&characterEncoding=utf8
username: root
password: root
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
package com.mlcp.config;
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
public class HibernateAutoConfiguration {
@Bean
public SessionFactory sessionFactory(EntityManagerFactory factory) {
if (factory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return factory.unwrap(SessionFactory.class);
}
}
查询
String sql="SELECT * FROM mlcp_node_result ORDER BY p_id";
return sessionFactory.openSession().createSQLQuery(sql).list();
你可能感兴趣的:(Springboot+hibernate 操作原生sql语句实现建表,插入数据和查询数据)