ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

spring boot——集成JPA——入门示例001

2022-05-29 19:03:43  阅读:142  来源: 互联网

标签:示例 JPA spring boot springframework id import org public


需要新增的依赖:

 

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

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

 

 

 

 

 

 

 

 

 

pom文件如下:

 

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.mohai.one</groupId>
	<artifactId>springboot-data-jpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-data-jpa</name>
	<description>spring-data-jpa整合实现</description>

	<properties>
		<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-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

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

</project>

  

 

 

 

 

 

 

 

 

 

 

 

 

 

application.yml配置信息:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mohai_demo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
    username: root
    password: 123456

  # JPA配置
  jpa:
    # 数据库类型
    database: mysql
    # 切换默认的存储引擎切换为InnoDB
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    # 输出日志中打印出执行的SQL语句
    show-sql: true
    # 配置程序在启动的时候自动操作实体类对应的表
    hibernate:
      #create:程序重新启动时,都会重新创建表,会造成数据会丢失
      #create-drop:每次运行程序时,会先创建表结构,然后待程序结束时清空表
      #upadte:每次运行程序时,实体对应没有表时会创建表,如果实体发生改变会更新表结构,原来数据不会清空只会更新
      #validate:每次运行程序时,会校验数据与数据库的字段类型是否相同
      ddl-auto: update

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

UserEntity类
package com.mohai.one.springbootjpa.domain;

import javax.persistence.*;

@Entity //必选注解,声明和数据库中user表关联
@Table(name = "user") //可选注解,声明实体对应的表信息
public class UserEntity {

    @Id // 表名实体唯一标识
    @GeneratedValue(strategy = GenerationType.IDENTITY) //主键自动生成策略
    private Integer id;
    //@Column定义列名和属性,默认为字段名
    @Column
    private String name;
    @Column
    private int age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

UserRepository

 

 

package com.mohai.one.springbootjpa.repository;

import com.mohai.one.springbootjpa.domain.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<UserEntity,Integer> {

    List<UserEntity> findAllByName(String name);

    @Modifying
    @Query(value = "insert into user(id,name,age) values(:id,:name,:age)",nativeQuery = true)
    int insertNameAndAge(@Param("id") Integer id, @Param("name") String name, @Param("age") int age);

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

UserService

 

package com.mohai.one.springbootjpa.service;

import com.mohai.one.springbootjpa.domain.UserEntity;
import com.mohai.one.springbootjpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    //查
    public List<UserEntity> getAll(){
        return userRepository.findAll();
    }

    //查
    public List<UserEntity> findAllByName(String name){
        return userRepository.findAllByName(name);
    }

    //通过id查询
    public UserEntity getOne(Integer id){
        return userRepository.findById(id).get();
    }

    //改
    @Transactional
    public UserEntity updateUser(UserEntity userEntity){
        return userRepository.saveAndFlush(userEntity);
    }

    //增
    @Transactional
    public int insertUser(UserEntity userEntity){
        return userRepository.insertNameAndAge(userEntity.getId(),userEntity.getName(),userEntity.getAge());
    }

    //删
    @Transactional
    public void deleteUserById(Integer id){
        userRepository.deleteById(id);
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

UserController

 

package com.mohai.one.springbootjpa.controller;

import com.mohai.one.springbootjpa.domain.UserEntity;
import com.mohai.one.springbootjpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Created by moerhai@qq.com
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAll")
    public List<UserEntity> findAll(){
        return userService.getAll();
    }

    @RequestMapping("/findAllByName")
    public List<UserEntity> findAllByName(String name){
        return userService.findAllByName(name);
    }

    //通过主键Id查询
    @RequestMapping("/getOne/{id}")
    public UserEntity getUserById(@PathVariable Integer id){
        return userService.getOne(id);
    }

    @RequestMapping("/save")
    public int save(@RequestBody UserEntity userEntity){
        return userService.insertUser(userEntity);
    }

    @RequestMapping("/edit")
    public UserEntity edit(@RequestBody UserEntity userEntity){
        return userService.updateUser(userEntity);
    }

    @RequestMapping("/delete")
    public int delete(@RequestParam("id") Integer id){
         userService.deleteUserById(id);
         return 1;
    }
}

 

 

标签:示例,JPA,spring,boot,springframework,id,import,org,public
来源: https://www.cnblogs.com/xiaobaibailongma/p/16324558.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有