廢話不多說直接上代碼樣例!附帶全部內容,包含資料庫以及表結構和資料
依賴
<!-- 如果有SpringBoot啟動器,就不加-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<!-- Springweb啟動器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringData-jpa啟動器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
物體類
- 物體類和表的映射關系
@Entity 表示物體類
@Table 表示和表的關系 - 類中屬性和表中欄位的映射關系
@Id 指明主鍵
@GeneratedValue 主鍵的生成策略
@Column 屬性和欄位對應關系,一般是欄位名和屬性名相差比較大使用
package com.lianxi.jpa.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Date;
/**
* 物體類和表的映射關系
@Entity 表示物體類
@Table 表示和表的關系
*類中屬性和表中欄位的映射關系
@Id 指明主鍵
@GeneratedValue 主鍵的生成策略
@Column 屬性和欄位對應關系,一般是欄位名和屬性名相差比較大使用
*/
@Entity
@Table(name ="lx_user")
@Data
@NoArgsConstructor
public class User{
// id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 用戶名
@Column(name ="user_name")
private String userName;
// 密碼
private String password;
// 姓名
private String name;
// 年齡
private Integer age;
// 性別,1男性,2女性
private Integer sex;
// 出生日期
private Date birthday;
// 創建時間
private Date created;
// 更新時間
private Date updated;
// 備注
private String note;
//用來測驗保存
public User(String userName, String password, String name, Integer age, Integer sex, String note) {
this.userName = userName;
this.password = password;
this.name = name;
this.age = age;
this.sex = sex;
this.note = note;
}
//用來測驗更新
public User(Long id,String userName, String password, String name, Integer age, Integer sex, String note) {
this.id=id;
this.userName = userName;
this.password = password;
this.name = name;
this.age = age;
this.sex = sex;
this.note = note;
}
}
資料庫以及表
/*
SQLyog Ultimate v12.08 (64 bit)
MySQL - 5.7.32 : Database - springdata_jpa
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springdata_jpa` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */;
USE `springdata_jpa`;
/*Table structure for table `lx_user` */
DROP TABLE IF EXISTS `lx_user`;
CREATE TABLE `lx_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_name` varchar(100) DEFAULT NULL COMMENT '用戶名',
`password` varchar(100) DEFAULT NULL COMMENT '密碼',
`name` varchar(100) DEFAULT NULL COMMENT '姓名',
`age` int(10) DEFAULT NULL COMMENT '年齡',
`sex` tinyint(1) DEFAULT NULL COMMENT '性別,1男性,2女性',
`birthday` date DEFAULT NULL COMMENT '出生日期',
`note` varchar(255) DEFAULT NULL COMMENT '備注',
`created` datetime DEFAULT NULL COMMENT '創建時間',
`updated` datetime DEFAULT NULL COMMENT '更新時間',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
/*Data for the table `lx_user` */
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (1,'zhangsan1','1234567','張三',25,1,'1964-08-08','張三同學在學Java','2014-09-19 16:56:04','2014-09-21 11:24:59');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (2,'lisi11','123456777','李四',21,1,'1995-01-01','李四同學在學Java','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (3,'wangwu','123456','王五',22,1,'1994-01-01','王五同學在學php','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (4,'zhangwei','123456','張偉',20,1,'1996-09-01','張偉同學在學Java','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (5,'lina','123456','李娜',28,0,'1988-01-01','李娜同學在學Java','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (6,'lilei','123456','李磊',23,1,'1993-08-08','李磊同學在學Java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (7,'yangmi','123456','楊冪',24,0,'1992-08-08','楊冪同學在學php','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (8,'liuyan','123456','柳巖',21,0,'1995-08-08','柳巖同學在學java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (9,'liuyifei','123456','劉亦菲',18,0,'1998-08-08','劉亦菲同學在學唱歌','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (10,'fanbingbing','123456','范冰冰',25,0,'1991-08-08','范冰冰同學在學java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (11,'zhengshuang','123456','鄭爽',23,0,'1993-08-08','鄭爽同學在學習java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (12,'tangyan','123456','唐嫣',26,0,'1990-08-08','唐嫣同學在學習java','2014-09-20 11:41:15','2014-09-20 11:41:15');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
啟動類
package com.lianxi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserSpringDataJpaApplication {
public static void main(String[] args) {
SpringApplication.run(UserSpringDataJpaApplication.class,args);
}
}
application.yml
server:
port: 7184
spring:
application:
name: springData-Jpa
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springdata_jpa?characterEncoding=UTF-8
username: root
password: root
jpa:
database: mysql # 指定資料庫
show-sql: true # 設定顯示SQL
generate-ddl: true # 設定Generate Ddl
controller
package com.lianxi.jpa.controller;
import com.lianxi.jpa.pojo.User;
import com.lianxi.jpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 查詢全部
* @return
*/
@GetMapping("/findAll")
public List<User> getUserFindAll(){
List<User> userList = userService.userFindAll();
//回傳結果
return userList;
}
/**
* 根據id查詢
*/
@GetMapping("/{id}")
public User getUserById(@PathVariable("id") Long id){
User user = userService.findById(id);
//回傳結果
return user;
}
/**
* 添加一條資料
* 為了測驗方便,就用GET請求了
*/
@GetMapping("/add/add")
public String userAdd(){
//構建添加資料
User user = new User("ceshi","123456","測驗1",18,1,"用來測驗");
//添加
String userAdd = userService.userAdd(user);
return userAdd;
}
/**
* 洗掉一條資料
* 為了測驗方便,就用GET請求了
*/
@GetMapping("/deleteById/{id}")
public String deleteById(@PathVariable("id") Long id){
String deleteById = userService.deleteById(id);
//回傳結果
return deleteById;
}
/**
* 根據id更新一條資料
* 為了測驗方便,就用GET請求了
* @param id
* @return
*/
@GetMapping("/updata/{id}")
public String updataById(@PathVariable("id") Long id){
//構建資料
User user = new User(id,"ceshi","12345666","測驗1",18,1,"用來測驗更新方法!!");
//呼叫更新方法
String updataById = userService.updataById(user);
//回傳結果
return updataById;
}
}
dao
繼承 JpaRepository介面提供了基本的增刪改查
繼承JpaSpecificationExecutor介面用于做復雜的條件查詢
package com.lianxi.jpa.dao;
import com.lianxi.jpa.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* JpaRepository提供了基本的增刪改查
* JpaSpecificationExecutor用于做復雜的條件查詢
*/
public interface UserDao extends JpaRepository<User,Long>, JpaSpecificationExecutor<User> {
}
service
package com.lianxi.jpa.service;
import com.lianxi.jpa.dao.UserDao;
import com.lianxi.jpa.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
private UserDao userDao;
/**
* 查詢全部
* @return
*/
public List<User> userFindAll() {
List<User> userDaoAll = userDao.findAll();
return userDaoAll;
}
/**
* 根據id查詢
*/
public User findById(Long id) {
User user = userDao.findById(id).get();
return user;
}
/**
* 添加一條資料
*/
public String userAdd(User user) {
try {
//保存
userDao.save(user);
return "保存成功";
} catch (Exception e) {
e.printStackTrace();
return "保存失敗";
}
}
/**
* 根據id洗掉
* @param id
* @return
*/
public String deleteById(Long id) {
try {
//保存
userDao.deleteById(id);
return "洗掉成功";
} catch (Exception e) {
e.printStackTrace();
return "洗掉失敗";
}
}
/**
* 根據id更新一條資料
* @param user
* @return
*/
public String updataById(User user) {
try {
//更新
userDao.save(user);
return "更新成功";
} catch (Exception e) {
e.printStackTrace();
return "更新失敗";
}
}
}
這篇文章是基本的CRUD,用來快速上手使用,沒有分頁查詢和多條件查詢,其它的之后的文章里會有
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/243814.html
標籤:java
上一篇:STS或eclipse中匯入新專案出現紅色感嘆號紅色叉叉的問題
下一篇:最小高度樹Java版本(力扣)
