SpringBoot在IDEA下使用JPA


1依赖

使用IDEA构建基于JPA的项目需要引用JPA、MYSQL依赖

 

2配置文件修改

2.1连接库

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=Aa123123

2.2开启jpa日志

spring.jpa.show-sql=true

3编写实体连接表

实体类增加注解

@Entity
@Table(name = "car")

主键增加注解

@Id()

 字段增加注解

@Column(name = "car_id")

4定义JPA接口类

JPA接口默认提供保存、delByID,如果额外需要查询和更新需要手动定义接口,其中使用update接口有两点需要注意:

1用户手动编写SQL放在@Query注解中;

2增加注解@Transactional、@Modifying用于update方法。

package com.cloud.jpa.repository;

import com.cloud.jpa.entity.Car;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;

@Repository
public interface FirstJpaRepository extends JpaRepository<Car, Integer> {

Car findByCarId(Integer carid);

Car findByCarName(String carName);

@Transactional
@Modifying
@Query(value = "update car c set c.car_name=? where car_id=?", nativeQuery = true)
int updateCarNameByCarId(String carName, Integer carId);
}

 5开始使用

搭建好上述环境后就可以实现基本的基于JPA的CRUD了

 

项目地址 https://github.com/MingHaiTian/springboot-jpa.git


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM