SpringBoot------JPA连接数据库
步骤:
1.在pom.xml文件下添加相应依赖包
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itsource</groupId>
<artifactId>springboot-shop</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-shop Maven Webapp</name>
<url>http://maven.apache.org</url> <!-- 如果添加了Parent,则dependency中可以不加入version,会自动匹配parent的版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency> <!-- 添加mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <!-- 添加spring-data-jpa依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <!-- 引入spring-data-jpa依赖,则不需要引入jdbc
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
--> <!-- 使用thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <!-- 使用devtool热部署插件(推荐) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies> <build>
<finalName>myshop</finalName>
<!-- 热部署插件 -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 这里得设置为true -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.在src/main/resources/application.properties文件下添加配置信息
server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-active=20
spring.datasource.tomcat.max-idle=8
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.initial-size=10 spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
3.创建一个实体类,例如:UserInfo
package myshop.bean; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator;
/**
* 使用@Entity进行实体类的持久化操作,当JPA检测到实体类中有@Entity注解时,
* 会在数据库中生成相应的表结构
*/
@Entity
public class UserInfo {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String username;
private String password; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
4.创建接口继承CrudRepository
package myshop.repository; import org.springframework.data.repository.CrudRepository; import myshop.bean.UserInfo; public interface UserInfoRepository extends CrudRepository<UserInfo, Integer> { }
6.创建一个Controller
package myshop.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import myshop.bean.UserInfo;
import myshop.service.UserInfoService; @RestController
@RequestMapping("/userinfo")
public class UserInfoController {
@Resource
private UserInfoService userInfoService; @RequestMapping("/save")
private String save()
{
UserInfo user = new UserInfo();
user.setUsername("陈超");
user.setPassword("2277092");
userInfoService.save(user);
return "save ok!";
} @RequestMapping("/update")
private String update()
{
userInfoService.update(2);
return "update ok!";
} @RequestMapping("/delete")
private String delete()
{
userInfoService.delete(1);
return "delete ok!";
} @RequestMapping("/getall")
private Iterable<UserInfo> getAll()
{
return userInfoService.getAll();
}
}
7.创建一个Service
package myshop.service; import javax.annotation.Resource;
import javax.transaction.Transactional; import org.springframework.stereotype.Service; import myshop.bean.UserInfo;
import myshop.repository.UserInfoRepository; @Service
public class UserInfoService {
@Resource
private UserInfoRepository userInfoRepository; /*
* save, update, delete方法需要绑定事物
*/
@Transactional
public void save(UserInfo user)
{
userInfoRepository.save(user);
} @Transactional
public void update(int id)
{
UserInfo user = userInfoRepository.findOne(id);
user.setUsername("玉天恒");
userInfoRepository.save(user);
} @Transactional
public void delete(int id)
{
userInfoRepository.delete(id);
} public Iterable<UserInfo> getAll()
{
return userInfoRepository.findAll();
}
}
8.创建启动类
package myshop; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; @SpringBootApplication
public class App { @Bean
public HttpMessageConverters fastJsonHttpMessageConverter()
{
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastConfig = new FastJsonConfig();
fastConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastConfig); HttpMessageConverter<?> converts = fastConverter;
return new HttpMessageConverters(converts);
} public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(App.class, args);
} }
9.代码测试
运行结果:
数据库shop会自动生成一张UserInfo的表
在地址栏输入以下地址进行测试
http://localhost:8080/userinfo/getall
http://localhost:8080/userinfo/save
http://localhost:8080/userinfo/update
http://localhost:8080/userinfo/delete
SpringBoot------JPA连接数据库的更多相关文章
- springboot使用Jpa连接数据库
springboot使用Jpa连接数据库 1.pom.xml: <?xml version="1.0" encoding="UTF-8"?> < ...
- Spring Boot JPA 连接数据库
本文将介绍怎样在Spring Boot project中加入JPA作为持久化方式. 改动 pom.xml 依赖 与上一篇介绍的 jdbc 不同的是 spring-boot-starter-jdbc 改 ...
- 补习系列(19)-springboot JPA + PostGreSQL
目录 SpringBoot 整合 PostGreSQL 一.PostGreSQL简介 二.关于 SpringDataJPA 三.整合 PostGreSQL A. 依赖包 B. 配置文件 C. 模型定义 ...
- 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础授权权限
上一篇<[原]无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限>介绍了实现Shiro的基础认证.本篇谈谈实现 ...
- 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限
开发环境搭建参见<[原]无脑操作:IDEA + maven + SpringBoot + JPA + Thymeleaf实现CRUD及分页> 需求: ① 除了登录页面,在地址栏直接访问其他 ...
- 带着新人学springboot的应用08(springboot+jpa的整合)
这一节的内容比较简单,是springboot和jpa的简单整合,jpa默认使用hibernate,所以本质就是springboot和hibernate的整合. 说实话,听别人都说spring data ...
- springboot+jpa+mysql+redis+swagger整合步骤
springboot+jpa+MySQL+swagger框架搭建好之上再整合redis: 在电脑上先安装redis: 一.在pom.xml中引入redis 二.在application.yml里配置r ...
- springboot+jpa+mysql+swagger整合
Springboot+jpa+MySQL+swagger整合 创建一个springboot web项目 <dependencies> <dependency> < ...
- SpringBoot JPA + H2增删改查示例
下面的例子是基于SpringBoot JPA以及H2数据库来实现的,下面就开始搭建项目吧. 首先看下项目的整体结构: 具体操作步骤: 打开IDEA,创建一个新的Spring Initializr项目, ...
- SpringBoot Jpa入门案例
版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons) 我们先来了解一下是什么是springboot jpa,springboo ...
随机推荐
- VBA中数据库导出数据到Excel注意事项
Sub ReadDBData() On Error GoTo ErrorHand Dim dbHelper As New dbHelper Dim sqlSQL As String Dim rs As ...
- 基于octree的空间划分及搜索操作
(1) octree是一种用于管理稀疏3D数据的树形数据结构,每个内部节点都正好有八个子节点,介绍如何用octree在点云数据中进行空间划分及近邻搜索,实现“体素内近邻搜索(Neighbors wi ...
- 微信小程序 --- e.currentTarget.dataset.id 获取不到值
直接代码 wxml代码片段 <view class='ranksList' wx:for="{{ranksLb}}"> <view class='ranksLis ...
- Linux之计划任务
计划任务特性 1. 需要在指定的某时间段运行 2. 需要将任务结果邮件通知用户 3. 单次任务及循环任务区别 Linux计划任务的实现工具 1. at工具 其只能执行一次性任务 其会自动加载部分环境变 ...
- SpringMVC系列(六)处理模型数据
Spring MVC 提供了以下几种途径输出模型数据: ModelAndView: 处理方法返回值类型为 ModelAndView时, 方法体即可通过该对象添加模型数据 Map 及 Model: ...
- e618. Validating a JTextField When Permanently Losing the Focus
This example demonstrates a text field that validates its contents when it receives a permanent focu ...
- Redis工业生产应用场景
Redis应用场景 国内外三个不同领域巨头分享的Redis实战经验及使用场景 Redis的5个常见使用场景 Redis应用场景 Redis应用场景<张善友>
- 创建自己的PKI公/私密钥对和公钥证书
1. 创建certificate request configuration file cert_req.conf******************************************* ...
- Xianfeng轻量级Java中间件平台:基于RBAC模型实现权限控制的原理
首先,白话一下RBAC模型.RBAC是基于角色的访问控制(Role-Based Access Control)的简称.RBAC认为权限授权实际上是Who.What.How的问题.在RBAC模型中,wh ...
- ggplot2 提取stat计算出来的数据
使用ggplot2 绘图时,我们只需要提供原始数据就可以了,ggplot2 内置了许多的计算函数,来帮助我们计算对应的数值. 最典型的的,当使用geom_boxplot 绘制箱线图时,我们只提供原始数 ...