文档章节

Spring boot + Jpa + Maven + Mysql 初级整合

o
 osc_z1hvg4cu
发布于 2018/04/24 21:32
字数 1785
阅读 21
收藏 0

精选30+云产品,助力企业轻松上云!>>>

1、使用Idea创建spring boot工程的博客

<font color='blue'><a href="https://www.cnblogs.com/black-spike/p/8017768.html">https://www.cnblogs.com/black-spike/p/8017768.html</a></font>

2、本篇博客参考网址

<font color='blue'><a href="https://blog.csdn.net/supervictim/article/details/54582083">https://blog.csdn.net/supervictim/article/details/54582083</a></font>

3、整个工程的目录文件如下

springboot02

4、在pom.xml配置文件中添加springboot依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from dao -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

5、application.properties配置文件

# 定位模板的目录
spring.mvc.view.prefix=classpath:/templates/
# 给返回的页面添加后缀名
spring.mvc.view.suffix=.html

spring.datasource.url = jdbc:mysql://localhost:3306/db_tosys
spring.datasource.username = root
spring.datasource.password = password
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

6、以上的pom.xml和application.properties,添加了springboot和thymeleaf依赖,以下查看SpringMvc实例

package com.example.demo.controller;

import com.example.demo.entity.Flight;
import com.example.demo.dao.FlightDao;
import com.example.demo.utils.DateJsonValueProcessor;
import com.example.demo.utils.ResponseUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/flight")
public class FlightController {

  private static final String format = "yyyy-MM-dd HH:mm:ss";

  @Autowired
  private FlightDao flightDao;

  @RequestMapping("/index")
  public String index(){
    return "flightList";
  }

  @RequestMapping("/list")
  @ResponseBody
  public String list(HttpServletResponse response) throws Exception {
    List<Flight> list = flightDao.getList();
    int count = flightDao.getCount();
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor(format));
    JSONArray rows = JSONArray.fromObject(list, jsonConfig);
    JSONObject result = new JSONObject();
    result.put("rows", rows);
    result.put("total", count);
    ResponseUtil.write(response, result);
    return null;
  }
}

7、thymeleaf模板如下,flightList.html(备注:里面的thymeleay模板必须创建在resource文件夹下面的templates文件夹下面,若此文件夹不存在则自行创建,以下之是显示列表显示部分字段)

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
    <title>获得Flight信息列表</title>

    <link th:href="@{/jquery-easyui-1.5.3/themes/default/easyui.css}" rel="stylesheet"/>
    <link th:href="@{/jquery-easyui-1.5.3/themes/icon.css}" rel="stylesheet"/>

    <script th:src="@{/jquery-easyui-1.5.3/jquery.min.js}"></script>
    <script th:src="@{/jquery-easyui-1.5.3/jquery.easyui.min.js}"></script>
    <script th:src="@{/jquery-easyui-1.5.3/locale/easyui-lang-zh_CN.js}"></script>

</head>
<body style="margin:1px;">
<table id="dg" class="easyui-datagrid" title="航班信息列表" style="height:500px" data-options="
            fit:true,
            rownumbers:true,
            autoRowHeight:true,
            pagination:true,
            SingleSelect:false,
            pageSize:20,
            pageList: [20, 30, 50],
            url:'/flight/list',
            method:'get',
            toolbar:'#tb'">
    <thead>
    <tr>
        <th field="cb" checkbox="true" align="center"></th>
        <th field="id" width="50" align="center">编号</th>
        <th field="name" width="150" align="center">航班名称</th>
        <th field="flighttype" width="100" align="center">航班类型</th>
        <th field="fromcity" width="100" align="center">出发城市</th>
        <th field="tocity" width="100" align="center">目的城市</th>
        <th field="fromtime" width="150" align="center">出发时间</th>
        <th field="totime" width="150" align="center">到点时间</th>
    </tr>
    </thead>
</table>
<div id="tb">
    <div>
        <a href="javascript:openFlightAddDialog()" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
        <a href="javascript:openFlightModifyDialog()" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>
        <a href="javascript:deleteFlight()" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
    </div>
    <div>
        &nbsp;航班名称:<input type="text" id="s_flightName" style="width: 100px"
                          onkeydown="if(event.keyCode==13) searchFlight()"/>
        &nbsp;出发地点:<input type="text" id="s_fromCity" style="width: 100px"
                          onkeydown="if(event.keyCode==13) searchFlight()"/>
        &nbsp;到达地点:<input type="text" id="s_toCity" style="width: 100px"
                          onkeydown="if(event.keyCode==13) searchFlight()"/>
        &nbsp;出发日期:<input type="text" id="s_fromTime" class="easyui-datebox" style="width: 100px"
                          onkeydown="if(event.keyCode==13) searchFlight()"/>
        <a href="javascript:searchFlight()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
    </div>
</div>

<div id="dlg" class="easyui-dialog" style="width: 700px;height:350px;padding: 10px 20px"
     closed="true" buttons="#dlg-buttons">
    <form id="fm" method="post">
        <table cellspacing="8px">
            <tr>
                <td>航班名称:</td>
                <td><input type="text" id="name" name="flight.name" class="easyui-validatebox" required="true"/></td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>航班类型:</td>
                <td>
                    <select class="easyui-combobox" id="flightType" name="flight.flightType" style="width: 154px;"
                            editable="false" panelHeight="auto">
                        <option value="">请选择性别</option>
                        <option value="国内航班">国内航班</option>
                        <option value="国际航班">国际航班</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>出发地点:</td>
                <td><input type="text" id="fromCity" name="flight.fromCity" class="easyui-validatebox" required="true"/>
                </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>出发时间:</td>
                <td><input type="text" id="fromTime" name="flight.fromTime" class="easyui-datetimebox" required="true"/>
                </td>
            </tr>
            <tr>
                <td>到达地点:</td>
                <td><input type="text" id="toCity" name="flight.toCity" class="easyui-validatebox" required="true"/>
                </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>到达时间:</td>
                <td><input type="text" id="toTime" name="flight.toTime" class="easyui-datetimebox" required="true"/>
                </td>
            </tr>
            <tr>
                <td>经济舱票价:</td>
                <td><input type="text" id="ecPrice" name="flight.ecPrice" class="easyui-validatebox" required="true"/>
                </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>(经济舱)座位数:</td>
                <td><input type="text" id="ecTicketTotal" name="flight.ecTicketTotal" class="easyui-numberbox"
                           required="true"/></td>
            </tr>
            <tr>
                <td>头等舱票价:</td>
                <td><input type="text" id="fcPrice" name="flight.fcPrice" class="easyui-validatebox" required="true"/>
                </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>(头等舱)座位数:</td>
                <td><input type="text" id="fcTicketTotal" name="flight.fcTicketTotal" class="easyui-numberbox"
                           required="true"/></td>
            </tr>
            <tr>
                <td>使用客机:</td>
                <td colspan="4">
                    <input class="easyui-combobox" id="aircraft" name="flight.aircraft.id"
                           data-options="panelHeight:'auto',editable:false,valueField:'id',textField:'name',url:'aircraft_comboList.action'"/>
                </td>
            </tr>
        </table>
    </form>
</div>

<div id="dlg-buttons">
    <a href="javascript:saveFlight()" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
    <a href="javascript:closeFlightDialog()" class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>
<script type="text/javascript">

 function searchFlight() {
        $("#dg").datagrid('load', {
            "s_flight.name": $("#s_flightName").val(),
            "s_flight.fromCity": $("#s_fromCity").val(),
            "s_flight.toCity": $("#s_toCity").val(),
            "s_flight.fromTime": $("#s_fromTime").datebox("getValue")
        });
    }
  
</script>
</body>
</html>

8、为mian方法添加一些注解

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.demo.dao")
@EntityScan(basePackages = "com.example.demo")
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

9、接下来创建实体层(entity,备注:字段全小写,若是驼峰式命名,查询结果可能出现问题)

package com.example.demo.entity;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name="t_flight")
public class Flight {

	@Id
	@GeneratedValue(strategy= GenerationType.AUTO)
	private int id; 
	private String name; 
	private String fromcity; 
	private String tocity; 
	private Date fromtime;
	private Date totime; 
	private int ecprice;
	private int fcprice; 
	private int ectickettotal; 
	private int fctickettotal; 
	private int ecticketremain; 
	private int fcticketremain; 
	private String flighttype;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFromcity() {
		return fromcity;
	}

	public void setFromcity(String fromcity) {
		this.fromcity = fromcity;
	}

	public String getTocity() {
		return tocity;
	}

	public void setTocity(String tocity) {
		this.tocity = tocity;
	}

	public Date getFromtime() {
		return fromtime;
	}

	public void setFromtime(Date fromtime) {
		this.fromtime = fromtime;
	}

	public Date getTotime() {
		return totime;
	}

	public void setTotime(Date totime) {
		this.totime = totime;
	}

	public int getEcprice() {
		return ecprice;
	}

	public void setEcprice(int ecprice) {
		this.ecprice = ecprice;
	}

	public int getFcprice() {
		return fcprice;
	}

	public void setFcprice(int fcprice) {
		this.fcprice = fcprice;
	}

	public int getEctickettotal() {
		return ectickettotal;
	}

	public void setEctickettotal(int ectickettotal) {
		this.ectickettotal = ectickettotal;
	}

	public int getFctickettotal() {
		return fctickettotal;
	}

	public void setFctickettotal(int fctickettotal) {
		this.fctickettotal = fctickettotal;
	}

	public int getEcticketremain() {
		return ecticketremain;
	}

	public void setEcticketremain(int ecticketremain) {
		this.ecticketremain = ecticketremain;
	}

	public int getFcticketremain() {
		return fcticketremain;
	}

	public void setFcticketremain(int fcticketremain) {
		this.fcticketremain = fcticketremain;
	}

	public String getFlighttype() {
		return flighttype;
	}

	public void setFlighttype(String flighttype) {
		this.flighttype = flighttype;
	}
}

10、创建dao层(注:此处创建一个FlightDao的接口,并不需要创建FlightDao的实现,springboot默认会帮我们实现,继承CruReposity,@Param代表的是sql语句中的占位符)

package com.example.demo.dao;

import com.example.demo.entity.Flight;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface FlightDao extends CrudRepository<Flight,Long> {

  @Query("select count(f) from Flight as f")
  int getCount();

  @Query("select f FROM Flight f")
  List<Flight> getList();

  //@Param代表的是sql语句中的占位符,例如这里的@Param(“name”)代表的是:name占位符。
 /* @Query("select t from User t where t.userName=:name")
  public User findUserByName(@Param("name") String name);*/
}

11、List列表结果集中时间(date)的工具类(DateJsonValueProcessor.java)

package com.example.demo.utils;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import java.text.SimpleDateFormat;

public class DateJsonValueProcessor implements JsonValueProcessor {

  private String format;

  public DateJsonValueProcessor(String format) {
    this.format = format;
  }

  public Object processArrayValue(Object value, JsonConfig jsonConfig) {
    return null;
  }

  public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
    if (value == null) {
      return "";
    }
    if (value instanceof java.sql.Timestamp) {
      String str = new SimpleDateFormat(format).format((java.sql.Timestamp) value);
      return str;
    }
    if (value instanceof java.util.Date) {
      String str = new SimpleDateFormat(format).format((java.util.Date) value);
      return str;
    }
    return value.toString();
  }
}

12、返回Json数据类型至页面的工具类(ResponseUtil.java)

package com.example.demo.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class ResponseUtil {

	public static void write(HttpServletResponse response, Object o)
			throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
}
o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。
Spring Boot:整合Spring Data JPA

综合概述 JPA是Java Persistence API的简称,是一套Sun官方提出的Java持久化规范。其设计目标主要是为了简化现有的持久化开发工作和整合ORM技术,它为Java开发人员提供了一种ORM工具来管理J...

朝雨忆轻尘
2019/06/18
0
0
Spring Boot:整合Spring Data JPA

综合概述 JPA是Java Persistence API的简称,是一套Sun官方提出的Java持久化规范。其设计目标主要是为了简化现有的持久化开发工作和整合ORM技术,它为Java开发人员提供了一种ORM工具来管理J...

osc_nd4uekgu
2019/06/18
1
0
Spring Boot 整合 JPA 使用多个数据源

介绍 JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 Hibernate 基础上封装的一款框架。第一次使用 ...

osc_b1b5q6vc
04/16
8
0
Spring Boot 整合 JPA 使用多个数据源

介绍 JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 Hibernate 基础上封装的一款框架。 第一次使用 ...

osc_46d1uuxp
2019/08/08
3
0
spring boot 1.5.4 整合JSP(四)

上一篇:springboot 1.5.4 之web开发(三) 1 Spring Boot添加JSP支持 Spring Boot默认是不支持jsp的,集成使用步骤: ① 新建spring-boot-jsp工程,工程源码: spring-boot相关项目源码, ...

wyait
2017/09/21
0
0

没有更多内容

加载失败,请刷新页面

加载更多

聊聊rocketmq-client-go的TraceInterceptor

序 本文主要研究一下rocketmq-client-go的TraceInterceptor TraceInterceptor rocketmq-client-go-v2.0.0/producer/interceptor.go // WithTrace support rocketmq trace: https://github.c......

go4it
47分钟前
0
0
如何在Android文本视图周围添加边框? - How do I put a border around an Android textview?

问题: 是否可以在textview周围绘制边框? 解决方案: 参考一: https://stackoom.com/question/EfXR/如何在Android文本视图周围添加边框 参考二: https://oldbug.net/q/EfXR/How-do-I-put...

法国红酒甜
今天
10
0
设计模式(4) 建造者模式

什么是建造者模式 经典建造者模式的优缺点 对建造者模式的扩展 什么是建造者模式 建造者模式将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。创建者模式隐藏了...

zhixin9001
今天
14
0
ArrayList源码分析 —— JDK8

ArrayList的特性 ArrayList内部使用数据作为存储结构,ArrayList可以理解为数组的扩展对象,封装了常用的和非常用的操作数组的方法。以及当数组长度不足以保存数组时,自动扩容数组,通常Arr...

XuePeng77
今天
56
0
__slots__的用法? - Usage of __slots__?

问题: Python中__slots__的目的是什么-尤其是关于何时以及何时不使用它的目的? 解决方案: 参考一: https://stackoom.com/question/1ymu/slots-的用法 参考二: https://oldbug.net/q/1ym...

富含淀粉
今天
17
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部